javascript 脊椎、node.js (express) 和 Access-Control-Allow-Origin

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10078173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 08:37:06  来源:igfitidea点击:

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

javascriptjqueryajaxnode.jsspine.js

提问by soupdiver

I'm developing an app on my local pc. THe frontend should be built with spinejs and the backend-api with node.js. Spine is running on port 9294 and node.js is running on port 3000. in Spine I've added to my model the following:

我正在本地电脑上开发一个应用程序。前端应该用spinejs 构建,后端api 应该用node.js 构建。Spine 在端口 9294 上运行,node.js 在端口 3000 上运行。在 Spine 中,我已将以下内容添加到我的模型中:

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

and in my express server

在我的快递服务器中

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

But I'm always getting the following erro in chrome:

但我总是在 chrome 中遇到以下错误:

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

What must I do that I can access my api properly? I though adding the header in the responses does fix the problem.

我必须做什么才能正确访问我的 api?我虽然在响应中添加标题确实解决了问题。

回答by Nathan Friedly

app.getwill only respond to GETrequests. If the browser is preflighting it with an OPTIONSrequest, express will send an error because it doesn't have any listeners for those requests. Try adding this code in addition to yours and see if it works:

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

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

Also note: if you're sending cookies with the request (withcredentials=true), then the Access-Control-Allow-Originheader cannot be *, it must be the exact value in the Originheader that the browser automatically adds to the ajax request like so:

另请注意:如果您使用请求 ( withcredentials=true)发送 cookie ,则Access-Control-Allow-Origin标头不能为*,它必须是Origin浏览器自动添加到 ajax 请求的标头中的确切值,如下所示:

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

This is for security reasons - if you're doing something that requires cookies, then it is more likely that you will want to actually check that the originis an allowed website in order to avoid CSRF attacks.

这是出于安全原因 - 如果您正在做一些需要 cookie 的事情,那么您更有可能希望实际检查该origin网站是否是允许的网站,以避免CSRF 攻击

回答by Troy Watt

This middleware will allow CORS using Express, the key is detecting the preflight request OPTIONSand returning a response to avoid 404's or duplicate database queries. See resource: http://cuppster.com/2012/04/10/cors-middleware-for-node-js-and-express/

该中间件将允许使用 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);