【发布时间】:2019-08-09 07:29:21
【问题描述】:
确切的错误消息:Access to XMLHttpRequest at 'http://localhost:7000/profile/picture?url=me' from origin 'http://localhost:8080' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我使用的是 express 版本 4.16.4。在我的应用程序中,上传图像并注销后,我在重新登录时收到此错误。我将以下内容添加到我的主服务器:
app.use('*', cors({
credentials: true,
origin: true,
methods: 'GET,HEAD,PUT,PATCH,POST,DELETE,OPTIONS',
preflightContinue: true
}));
... (routes here)
app.all('*', function (req, res, next) {
origin = req.get('origin');
// Development whitelist
var whitelist = ['http://localhost:8080', 'http://localhost:8081'];
corsOptions = {
origin: function (origin, callback) {
var originIsWhitelisted = whitelist.indexOf(origin) !== -1;
callback(null, originIsWhitelisted);
}
};
next();
});
我收到了OPTIONS 日志,但没有一条路由被命中。在 Node 中也不会抛出任何错误消息。
【问题讨论】:
-
为什么
preflightContinue是真的?后面的 .all 是为了什么?它似乎没有做任何事情。 -
@KevinB 我试图将节点应用程序限制为仅与我的 vue 应用程序通信。
-
为了让它工作,它需要在 路由之前出现,否则它可能根本不会运行。但是您在其中的代码实际上并没有做任何事情。您定义了三个包含对象或字符串的变量,然后……调用 next()。您可以使用这样的功能代替您的第一个功能,只允许 CORS 进入您的白名单,但您不应该同时使用这两种功能。第一个应该足以允许 CORS 请求,假设您在某个时候正确检测到 OPTIONS 请求并以 200 响应或将 preflightContinue 更改为 false。
-
我现在收到此错误:
...has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'. The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute. -
是的,不能使用“true”作为凭证请求的来源选项。您需要将其替换为返回原始值的回调。 (这是白名单发生的地方)github.com/expressjs/cors
标签: node.js express cors xmlhttprequest