NodeJS and Backbone's fetch

Problem

This is my front-end code (using 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);
        }
    });

and this is my back-end code (using 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();
});

The problem is that although the response is as expected, the client-side error callback is called. When I remove the line response.write('{test:1}');, the success callback is called. Any ideas as to what I might be doing wrong?

Problem courtesy of: Randomblue

Solution

Well {test:1} is not valid JSON.

{ "test":"1" } OR { "test":1 } is however, try one of those instead.

Keys are strings in JSON, and strings in JSON must be wrapped in double quotes check out JSON.org for more information.

To ensure you have valid JSON for more complex objects just use JSON.stringify():

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

Also, the correct Content-Type for json is application/json

Solution courtesy of: Chad

Discussion

{test:1} isn't valid JSON, you should try { "test":"1" }.

Another solution is to check Express's render.json function to see how it does sending json to the browser:

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

Discussion courtesy of: alessioalex

If you're using express you need to res.send will automatically convert objects into JSON. If you're worried about it, there's a new one called res.json that will convert anything into JSON.

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

You don't need need writeHead(), write(), or end().

http://expressjs.com/guide.html

Discussion courtesy of: Jamund Ferguson

This recipe can be found in it's original form on Stack Over Flow.