编辑:凯文B在下面的评论中回答了我的问题。我添加了一些逻辑来发送一个200请求,如果一个OPTIONS http请求命中我的API来解决这个问题。下面是代码:CORS请求在发送授权标头时不起作用
var allowCrossDomain = function(req, res, next) {
if ('OPTIONS' == req.method) {
res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,PATCH,OPTIONS');
res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With');
res.send(200);
}
else {
next();
}
};
router.use(allowCrossDomain);
原题: 我目前想获得在我的本地运行的离子2应用程序能够将数据发送到一个Express 4的应用程序。当我发送没有授权头的请求时,它可以工作。但是,一旦我添加了auth头文件,我的API就开始抛出错误。我已经做了我的研究,并试图实现什么,我在这里找到:(https://stackoverflow.com/a/15254158/5379931
不过,我仍然得到错误,如果我设置访问控制允许来源是这样的:
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
我得到这个错误:
XMLHttpRequest cannot load URL. Response to preflight request doesn't pass
access control check: The 'Access-Control-Allow-Origin' header has a value
'http://localhost:8100/' that is not equal to the supplied origin. Origin
'http://localhost:8100' is therefore not allowed access.
如果我把我的访问控制允许来源标题是这样的:
res.header("Access-Control-Allow-Origin", "http://localhost:8100/");
我得到这个错误:
XMLHttpRequest cannot load URL. No 'Access-Control-Allow-Origin' header is
present on the requested resource. Origin 'http://localhost:8100' is
therefore not allowed access. The response had HTTP status code 400.
这里是我的Express 4的代码的其余部分是相关的:
router.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "http://localhost:8100");
res.header("Access-Control-Allow-Headers", "Origin, Authorization, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Credentials", true);
res.header("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
next();
});
您声称自己正在设置的内容与您收到的错误消息之间似乎存在不匹配。您引用的第一条消息说:“'Access-Control-Allow-Origin'标头的值为 'http:// localhost:8100 /'”,这表示您的服务器配置为发送值为http:// localhost:8100 /',尾随斜线。没有其他方式可以将斜线添加到值中。然而,当你看到这条消息时,你声称你已经配置了服务器发送值“http:// localhost:8100”,没有结尾的斜杠。这是没有意义的。我认为你需要重新检查 – sideshowbarker
要清楚:服务器需要配置为发送值为“http:// localhost:8100”而没有结尾的斜杠 - 因为原始值不包含路径,而“Origin”请求头浏览器发送的是“http:// localhost:8100”(没有结尾的斜杠),所以你的Access-Control-Allow-Origin必须与*匹配,否则必须是*。 – sideshowbarker
您可能忘记了实际*回应*选项请求。你确实设置了标题,但是如果你没有回应它,你就去你的错误处理程序。 –