sou*_*ver 11 javascript ajax jquery node.js spine.js
我正在我的本地电脑上开发一个应用程序.应该使用spinejs构建前端,使用node.js构建后端api.Spine在端口9294上运行,node.js在端口3000上运行.在Spine中我已将以下内容添加到我的模型中:
@url: "http:localhost:3000/posts"
Run Code Online (Sandbox Code Playgroud)
在我的快递服务器上
app.get('/posts', function(req, res){
console.log("giving ALL the posts");
res.header("Access-Control-Allow-Origin", "*")
res.json(posts);
});
Run Code Online (Sandbox Code Playgroud)
但我总是在chrome中获得以下错误:
XMLHttpRequest cannot load http://localhost:3000/posts. Origin http://localhost:9294 is not allowed by Access-Control-Allow-Origin.
Run Code Online (Sandbox Code Playgroud)
我该怎么做才能正确访问我的api?我虽然在响应中添加标题确实解决了问题.
Nat*_*dly 16
app.get只会回应GET请求.如果浏览器使用OPTIONS请求对其进行预检,则express将发送错误,因为它没有任何侦听这些请求.尝试添加此代码以及您的代码,看看它是否有效:
app.options('/posts', function(req, res){
console.log("writing headers only");
res.header("Access-Control-Allow-Origin", "*");
res.end('');
});
Run Code Online (Sandbox Code Playgroud)
另请注意:如果您使用request(withcredentials=true)发送cookie ,那么Access-Control-Allow-Origin标头不能*,它必须是Origin浏览器自动添加到ajax请求的标头中的确切值,如下所示:
res.header("Access-Control-Allow-Origin", req.headers.origin);
Run Code Online (Sandbox Code Playgroud)
这是出于安全原因 - 如果您正在执行需要cookie的操作,那么您更有可能希望实际检查origin是否是允许的网站以避免CSRF攻击.
Tro*_*att 15
这个中间件将允许使用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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
15646 次 |
| 最近记录: |