0

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
Randomblue
  • 112,777
  • 145
  • 353
  • 547

3 Answers3

4

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

Community
  • 1
  • 1
Chad
  • 19,219
  • 4
  • 50
  • 73
  • Thanks a lot! That was indeed the problem. – Randomblue Dec 23 '11 at 15:32
  • Is there a way to know more information about the error? In the future I would like to be told that it's the JSON that is invalid... – Randomblue Dec 23 '11 at 15:34
  • I'm not a big `node.js` or `backbone` guy. I would guess that the error response has some information in it though; if not I would post another question, sorry.. – Chad Dec 23 '11 at 15:36
  • Of course you could always just build a JS object: `{ test: 1 }` and stringify it so that it is always valid: `JSON.stringify({ test: 1 })` – Chad Dec 23 '11 at 15:37
2

{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

alessioalex
  • 62,577
  • 16
  • 155
  • 122
1

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

Jamund Ferguson
  • 16,721
  • 3
  • 42
  • 50