我正在本地电脑上开发一个应用程序。前端应该使用 spinjs 构建,后端 API 应该使用 node.js。 Spine 在端口 9294 上运行,node.js 在端口 3000 上运行。 在 Spine 中,我在模型中添加了以下内容:
@url: "http:localhost:3000/posts"
在我的 express 服务器中
app.get('/posts', function(req, res){
console.log("giving ALL the posts");
res.header("Access-Control-Allow-Origin", "*")
res.json(posts);
});
但我总是在 chrome 中收到以下错误:
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('');
});
另请注意:如果您通过请求 (withcredentials=true
) 发送 cookie,则 Access-Control-Allow-Origin
header 不能是 *
,它必须是浏览器自动添加到 ajax 请求的 Origin
header 中的确切值,如下所示:
res.header("Access-Control-Allow-Origin", req.headers.origin);
这是出于安全原因 - 如果您正在执行需要 cookie 的操作,那么您更有可能需要实际检查 origin
是否为允许的网站,以避免 CSRF attacks .
关于javascript - 脊椎、node.js (express) 和 Access-Control-Allow-Origin,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10078173/