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
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));
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*
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With