编辑:Kevin B在下面的评论中回答了我的问题。如果OPTIONS http请求命中我的API来修复问题,我添加了一些逻辑来发送200请求。这是代码:
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);
原始问题: 我目前正在尝试在我的localhost上运行一个Ionic 2应用程序,以便能够将数据发送到Express 4应用程序。它在没有授权标头的情况下发送请求时有效。但是,一旦我添加了auth标头,我的API开始抛出错误。我完成了我的研究并尝试实现我在此处找到的内容:(https://stackoverflow.com/a/15254158/5379931。
但是,我仍然会收到错误。如果我像这样设置Access-Control-Allow-Origin:
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.
如果我像这样设置我的Access-Control-Allow-Origin标头:
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.
以下是我的快递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();
});
答案 0 :(得分:2)
您似乎忘了回复选项请求。如果没有响应,它将转到您的错误处理程序并被处理,就好像它是一个错误。
如果它是一个选项请求,只需在您的.use中发送200状态,以便它不会到达您的错误处理程序。