成功的请求在错误挂钩中被解包

时间:2015-06-08 21:09:23

标签: mithril.js

我有一个想要读入对象的模拟json文件。我的代码如下所示:

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");
});

代码始终只会点击unwrapError挂钩。

令我困惑的是这两件事:

  • 请求成功 - 我可以在Chrome的开发工具中看到它。没有任何迹象表明访问错误;
  • 错误钩子收到的第一个参数是我期望的JSON;第二个参数是相应的XMLHttpRequest对象,没有任何错误指示。

documentation相反,响应对象不包含“错误”属性,告诉我发生了什么。

我做错了什么?

1 个答案:

答案 0 :(得分:2)

我做了一个示例,展示了如何使用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(); }
});

在此测试:http://jsfiddle.net/ciscoheat/LL41sy9L/

编辑:实际问题是本地文件正在发出ajax请求。 Chrome不允许来自file://网址的Ajax来电。使用像http-server这样的简单Web服务器来处理Node.js将解决这个问题。