NodeJS和Backbone的获取

时间:2011-12-23 15:26:49

标签: javascript node.js backbone.js

这是我的前端代码(使用fetch

    var MyModel = Backbone.Model.extend();
    var MyCollection = Backbone.Collection.extend({
        url: '/questions',
        model: MyModel
    });
    var coll = new MyCollection();
    coll.fetch({
        error: function (collection, response) {
            console.log('error', response);
        },
        success: function (collection, response) {
            console.log('success', response);
        }
    });

这是我的后端代码(使用app.get

app.get('/questions', function (request, response) {
    console.log('Inside /questions');
    response.writeHead(200, {
        'Content-Type': 'text/json'
    });
    response.write('{test:1}');
    response.end();
});

问题是虽然响应符合预期,但会调用客户端error回调。当我删除行response.write('{test:1}');时,会调用success回调。关于我可能做错什么的任何想法?

3 个答案:

答案 0 :(得分:4)

{test:1}无效JSON。

{ "test":"1" } 要么 { "test":1 }  然而,请尝试其中一个。

键是JSON中的字符串,JSON中的字符串必须用双引号括起来,请查看JSON.org以获取更多信息。

为确保您拥有更复杂对象的有效JSON,请使用JSON.stringify()

var obj = { test : 1 };
response.write(JSON.stringify(obj)); //returns "{"test":1}"

此外,correct Content-Type for jsonapplication/json

答案 1 :(得分:2)

{test:1}无效JSON,您应该尝试{ "test":"1" }

另一个解决方案是检查Express的render.json函数,看看它如何将json发送到浏览器:

https://github.com/visionmedia/express/blob/master/lib/response.js#L152-172

答案 2 :(得分:1)

如果你正在使用express,你需要res.send会自动将对象转换为JSON。如果您对此感到担忧,可以使用一个名为res.json的新程序将任何内容转换为JSON。

var obj = {super: "man"}
res.send(obj) // converts to json
res.json(obj) // also converts to json

您不需要writeHead(),write()或end()。

http://expressjs.com/guide.html

相关问题