NodeJS and Backbone's fetch
NodeJS and Backbone's fetch
这是我的前端代码(使用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);
}
});
这是我的后端代码(使用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();
});
问题是,虽然响应是预期的,客户端error
回调被调用。当我删除行response.write('{test:1}');
时,调用success
回调。你知道我哪里做错了吗?
{test:1}
是无效的JSON。
{ "test":"1" }
或{ "test":1 }
但是,请尝试其中一个。
键是JSON中的字符串,JSON中的字符串必须用双引号括起来,查看JSON.org了解更多信息。
要确保您有更复杂的对象的有效JSON只需使用JSON.stringify()
:
var obj = { test : 1 };
response.write(JSON.stringify(obj)); //returns "{"test":1}"
另外,json的正确Content-Type是application/json
{test:1}
不是有效的JSON,您应该尝试{ "test":"1" }
。
另一个解决方案是检查Express的渲染。Json函数,看看它是如何向浏览器发送Json的:
https://github.com/visionmedia/express/blob/master/lib/response.js l152 - 172
如果您使用express,则需要res.send将自动将对象转换为JSON。如果你担心它,有一个名为res.json的新工具可以将任何内容转换为JSON。
var obj = {super: "man"}
res.send(obj) // converts to json
res.json(obj) // also converts to json
你不需要需要writeHead(), write()或end()
http://expressjs.com/guide.html相关文章:
- fetch() 函数未在 Ubuntu Chromium 浏览器上定义
- 当json解析空响应时,Whatwg-Fetch失败,我该如何防止它
- Selenium WebDriver and JavaScript change
- PHP and Javascript functions
- Javascript Return and if/else
- SetTimeout and clearTimeout in Javascript
- lightbox in html 5 and javascript
- TimelineJS and AngularJS
- timeago.js with datatable and PHP
- javascript button ajax and php
- Ajax and Json with Rails
- Combine onload, onresize and onclick
- IE11中的第二个调用取消了第一个Fetch API调用
- php布尔值's小写AND大写和数字布尔值'可以接受
- Fetch API and Cordova
- JS Fetch api and Symfony2 FOSRestBundle
- Backbone fetch,promise and if else.它们是如何工作的
- Blogger JSON API Post fetch and Content Parse
- NodeJS and Backbone's fetch
- ReactJS componentDidMount and Fetch API