如何在 express 中正确管理 CORS 策略? [英] How to manage CORS policy properly in express?

查看:15
本文介绍了如何在 express 中正确管理 CORS 策略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试允许从任何地方访问.

I am trying to allow access from everywhere.

我尝试过使用应用中间件:

I have tried using app middleware:

app.use(function (req, res, next) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  next();
});

我已经尝试在路由中使用它:

I have tried using it in the route:

app.post('/login',function(req,res){
var login   = req.body;
var sess    = req.session;

if (!login.email && !login.pwd){    
    return res.status(401);
}
res.header("Access-Control-Allow-Origin", '*');
res.header("Access-Control-Allow-Headers", '*');
.... more code here

两者都不起作用.我不断收到错误消息:对预检请求的响应未通过访问控制检查:请求的资源上不存在Access-Control-Allow-Origin"标头."

Both do not work. I keep getting an error: "Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource."

在服务器的下方,我们对另一条路线使用类似的代码,这很有效:

Further down the server, we use similar code for another route, which works:

app.post('/questar',function(req,res){
//allow xhr post from retireup domains
var cors = {
    origin: "https://www.website.com";
};
res.header("Access-Control-Allow-Origin", cors.origin);
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
res.type('application/json');

我无法分辨代码之间的区别,但只有一组有效.任何想法为什么?这似乎是一个不应该如此复杂的问题.谢谢

I cannot tell the difference between the code, but only one set works. Any ideas why? This seems like an issue that shouldn't be so complicated. Thanks

推荐答案

MDN 非常简短地解释了服务器应该如何响应 预检请求.

MDN has a very short explanation on how a server should respond to a Preflight Request.

您通过处理 HTTP OPTIONS 方法来处理 CORS 预检请求(就像您处理 GET 和 POST 方法一样)在处理同一路由上的其他请求方法之前:

You handle CORS preflight requests by handling the HTTP OPTIONS method (just like you would handle GET and POST methods) before handling other request methods on the same route:

app.options('/login', ...);
app.get('/login'. ...);
app.post('/login'. ...);

在您的情况下,它可能就像将您的 app.use() 调用更改为 app.options() 一样简单,将路由作为第一个参数传递,设置适当的标头,然后结束响应:

In your case, it might be as simple as changing your app.use() call to app.options(), passing the route as the first argument, setting the appropriate headers, then ending the response:

app.options('/login', function (req, res) {
  res.setHeader("Access-Control-Allow-Origin", "*");
  res.setHeader('Access-Control-Allow-Methods', '*');
  res.setHeader("Access-Control-Allow-Headers", "*");
  res.end();
});
app.post('/login', function (req, res) {
  ...
});

这篇关于如何在 express 中正确管理 CORS 策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆