spine,node.js(express)和Access-Control-Allow-Origin

我正在开发我的本地电脑上的应用程序。 前端应该用spinejs和后端api和node.js一起构build。 Spine在端口9294上运行,node.js在端口3000上运行。在Spine中,我添加了以下模型:

@url: "http:localhost:3000/posts" 

并在我的快递服务器

 app.get('/posts', function(req, res){ console.log("giving ALL the posts"); res.header("Access-Control-Allow-Origin", "*") res.json(posts); }); 

但我总是得到铬下面的错误:

 XMLHttpRequest cannot load http://localhost:3000/posts. Origin http://localhost:9294 is not allowed by Access-Control-Allow-Origin. 

我必须做什么,我可以正确访问我的API? 我虽然在响应中添加标题确实解决了问题。

app.get只会响应GET请求。 如果浏览器使用OPTIONS请求进行预检,则express将发送一个错误,因为它没有任何这些请求的侦听器。 尝试添加此代码除了你的,看看它是否工作:

 app.options('/posts', function(req, res){ console.log("writing headers only"); res.header("Access-Control-Allow-Origin", "*"); res.end(''); }); 

另外请注意:如果您发送的请求中带有cookie( withcredentials=true ),那么Access-Control-Allow-Origin头部不能是* ,它必须是Origin头部中的确切值,浏览器自动添加到ajax像这样请求:

 res.header("Access-Control-Allow-Origin", req.headers.origin); 

这是出于安全原因 – 如果你正在做一些需要cookies的事情,那么你很可能会想要真正检查origin是一个允许的网站,以避免CSRF攻击 。

这个中间件将允许使用Express的CORS,关键是检测预检请求OPTIONS并返回一个响应,以避免404或重复的数据库查询。 见资源: http : //cuppster.com/2012/04/10/cors-middleware-for-node-js-and-express/

 var methodOverride = require('method-override'); app.use(methodOverride()); // ## CORS middleware // see: http://stackoverflow.com/questions/7067966/how-to-allow-cors-in-express-nodejs var allowCrossDomain = function(req, res, next) { res.header('Access-Control-Allow-Origin', '*'); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization'); // intercept OPTIONS method if ('OPTIONS' == req.method) { res.send(200); } else { next(); } }; app.use(allowCrossDomain);