集成骨干与Nodejs

尝试从骨干模型获取Nodejs响应。

更新
更改模型代码如下,并获得错误

XMLHttpRequest无法加载http://localhost:3000/getDifficulty 。 请求的资源上没有“Access-Control-Allow-Origin”标题。 原因'null'因此不被允许访问。

 var Bitcoin = Backbone.Model.extend({ url:'http://localhost:3000/getDifficulty' }); var info = new Bitcoin (); info.fetch(); 

节点的JS是非常直接的,并为http://localhost:3000/getDifficulty

服务器端节点JS

 var http = require('http'), express = require('express'), bitcoin = require('bitcoin'); var app = express(); var client = new bitcoin.Client({ host: 'localhost', port: 8332, user: 'himanshuy', pass: 'xxx' }); app.get('/getDifficulty', function(req, res) { client.getInfo(function(err, info) { if(err) { res.send('Bitcoin error: '+ err); } else { res.send('Difficulty: ' + info); } }); }); app.listen(3000); 

客户端骨干模型

 var Bitcoin = Backbone.Model.extend({ urlRoot:'http://localhost:3000/getDifficulty' }); var info = new Bitcoin(); 

如果给这样的模型带来一些价值,它会正常工作

 var info = new Bitcoin({version:"1.0.0.", balance:"20.03"}); 

这意味着模型没有得到从URL的结果。
请帮忙。

注意:我对骨干和Nodej都是比较新的

尝试使用

 var Bitcoin = Backbone.Model.extend({ url:'getDifficulty' }); var info = new Bitcoin(); info.fetch(); 

看看控制台,看看服务器的响应。 从外观来看,上面的代码不起作用,因为你没有返回一个json对象res.send('Difficulty: ' + info) 。 骨干希望提供JSON数据(只有JSON),所以它可以将值加载到模型实例中。

如果从服务器返回的内容在加载到modekl之前需要修改,则需要实现parse函数(请参阅http://backbonejs.org/#Model-parse ):

 var Bitcoin = Backbone.Model.extend({ url:'getDifficulty', parse: function(response){ // the return value should be what needs to loaded into the model // for example, if we need to only have the `data`attribute in the model: return response.data; } }); 

如果你得到像这样的错误

 No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. 

您可能需要configuration浏览器来禁用CORS或networking安全设置。 这个Chrome扩展应该避免这个错误。

在Firefox中, 强制CORS扩展是有帮助的。

使用特定命令行参数启动Chrome也可以防止这些types的错误,但是像XSS这样的恶意代码会变得更容易受到影响:在目标字段的Windows上,这起作用 – 同时也降低了浏览器的安全性:

 "C:\Program Files\Google\Chrome\Application\chrome.exe" --disable-web-security