CORS表示无法正常工作 [英] CORS express not working predictably

查看:99
本文介绍了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 关于服务器应如何响应 Preflight请求

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

您可以通过处理HTTP OPTIONS方法(就像您处理GET和POST方法一样)来处理CORS飞行前请求,之前在同一路径上处理其他请求方法:

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一样简单。 ()调用 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) {
  ...
});

这篇关于CORS表示无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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