node.js - 被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头 [Nodejs]
问题描述
确切的错误信息: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.
我正在使用快速版本 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.js 中也不会抛出任何错误消息。
解决方案
试试这个方法:
const whitelist = [
'http://localhost:8080',
'http://localhost:8081'
];
const corsOptions = (origin) => {
return whitelist.some(wl=> wl.localeCompare(origin) === 0);
};
app.use( (req, res, next) => {
res.setHeader('Access-Control-Allow-Credentials', true);
res.setHeader('Access-Control-Allow-Origin', '*');
res.setHeader('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Accept');
if(!corsOptions(req.headers.origin)){
const error = {
erro : "This aren't a public API."
};
res.sendStatus(500).json(error);
next();
}
if ('OPTIONS' == req.method) {
res.sendStatus(200);
} else {
next();
}
});
推荐阅读
- javascript - 在 Svelte 应用程序中使用 rollup.js 时,如何在设计或编译时更严格地检查错误?
- ios - 我应该删除生产的firebase调试吗
- c++ - C ++(修改)中的选择排序不适用于所有情况
- javascript - Adding a JSON Response to a HighCharts Graph
- python - 函数中的 Python Base64 解码失败错误
- laravel - laravel 6:在 null 上调用成员函数 store()
- mysql - 为什么 Mysql 解释使用索引来跟踪 SQL 语句而不是范围
- python - 为什么 range 只在 python 中打印出(开始,结束)索引项(对我来说),而 quit() 对我也不起作用
- python - Python - 我有一个由函数(键和值)组成的字典,如何只获取值的 arg(而不是函数的结果)
- swift - 如何修复实例成员不能在类型 segmentedControl 上使用