NodeJS and Backbone's fetch


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();
        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'

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


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 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


{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:

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().

Discussion courtesy of: Jamund Ferguson

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