Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't fetch JSON In Backbone collection

I have the follow Backbone.js code

var List = Backbone.Collection.extend({
    model: Item,
    url: '/api/items',
});

and then in my view I'm trying to do the following to fetch the JSON from the API and populate the models

this.collection = new List();

var that = this;
this.collection.fetch({
    success: function () {
        that.render();
        console.log('Fetch successful!');
    },
    error: function() {
        console.log('Failed to fetch!');
    }
});

However the fetch is not working and its triggering the "Failed to fetch!" message. Can anyone see anything I'm doing wrong? If I go to the api/items in my browser I get prompted to download the JSON file so its definitely there and when I open it up its new line delimited. Below is a snippet of the api code that sends back the JSON

res.writeHead(200, {
    'Content-Type': 'application/x-json-stream'
});

setTimeout(function () {
    var i;
    for (i=0; i<limit; i+=1) {
        res.write(JSON.stringify(createRandomItem(i+skip, sort)) + '\n');
    }
    res.end();
}, 100 + Math.floor(Math.random() * 3000));

Also when I use developer tools to check the request that was sent to the API the response I get back just seems to be random characters and I get the error "SyntaxError: JSON.parse: Unexpected character"

eyJpZCI6IjAtd202MzNjYTF0Y3ZqOWs5Iiwic2l6ZSI6MTYsInByaWNlIjo5MzgsImZhY2
like image 917
Bender Avatar asked Jan 12 '15 16:01

Bender


2 Answers

Your response writing loop generate invalid json string, because it just concatenate json objects.

You can gather all objects in array and stringify it like this:

setTimeout(function () {
    var i, data = [];
    for (i=0; i<limit; i+=1) {
        data.push(createRandomItem(i+skip, sort));
    }

    res.write(JSON.stringify(data));
    res.end();
}, 100 + Math.floor(Math.random() * 3000));
like image 189
ertrzyiks Avatar answered Oct 22 '22 09:10

ertrzyiks


Typically, when you get a JSON.parse: unexpected character error, it indicates that the JSON attributes are not double-quote-qualified, so basically the JSON might look like this:

"{ test: 1, testing: 2 }"          *Invalid*

Or even this:

"{ 'test': 1, 'testing': 2 }"      *Invalid*

Instead of like this:

'{ "test": 1, "testing": 2 }'      *Valid*

Or this:

"{ \"test\": 1, \"testing\": 2 }"  *Valid*
like image 21
jeffdill2 Avatar answered Oct 22 '22 08:10

jeffdill2