NodeJS and Backbone's fetch

NodeJS and Backbone's fetch

本文关键字:fetch and Backbone NodeJS      更新时间:2023-09-26

这是我的前端代码(使用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回调。你知道我哪里做错了吗?

{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}"
另外,json的正确Content-Type是application/json

{test:1}不是有效的JSON,您应该尝试{ "test":"1" }

另一个解决方案是检查Express的渲染。Json函数,看看它是如何向浏览器发送Json的:

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

如果您使用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