Successful requests get unwrapped in error hook

216 views Asked by At

I have a mock json file that I want to read into an object. My code looks like this:

m = require('mithril');

/* .. snip .. */

var foo = m.prop([]);

m.request({
    method: 'GET',
    url: './foo.json',
    unwrapSuccess: function (a, b) {
        console.log("success");
    },
    unwrapError: function (a, b) {
        console.log("error");
    }
}).then(function (a) {
    // fill in foo
    console.log("object filled");
});

The code always hits only the unwrapError hook.

What is really confusing me are these two things:

  • The request is made successfully - I can see it in Chrome's dev tools. There is no indication of access error whatsoever;
  • The first argument received by the error hook is the very JSON I expect; the second argument is the corresponding XMLHttpRequest object, without any indication of error.

So contrary to the documentation, the response object does not contain an "error" property telling me what happened.

What am I doing wrong?

1

There are 1 answers

3
ciscoheat On BEST ANSWER

I made an example that shows how to use unwrapSuccess/unwrapError:

// No need for m.prop since m.request returns a GetterSetter too
var foo = m.request({
    method: 'GET',
    url: '//api.ipify.org?format=json',
    unwrapSuccess: function (a, b) {
        console.log("success: " + a.ip);
        // Remember to return the value that should be unwrapped
        return a.ip;
    },
    unwrapError: function (a, b) {
        console.log("error");
    }
}).then(function (ip) {
    console.log("object almost filled");
    // And remember to return the value to the GetterSetter
    return ip;
});

m.mount(document.getElementById('content'), { 
    view: function() { return "Your IP: " + foo(); }
});

Test it here: http://jsfiddle.net/ciscoheat/LL41sy9L/

Edit: The actual problem was that a local file was making the ajax request. Chrome disallow ajax calls from file:// URLs. Using a simple web server like http-server for Node.js will take care of that problem.