我有一个非常简单的nodejs服务器,但是由于某些原因,使用'cors'软件包似乎无法识别请求的来源。
这是我的nodejs服务器配置:
const cors = require('cors');
const express = require('express');
const CORS_WHITELIST = [ 'http://localhost:5000' ];
const corsOptions = {
origin: (origin, callback) => {
console.log(origin) // ----> this is always 'undefined'
if (CORS_WHITELIST.indexOf(origin) !== -1){
callback(null, true)
} else {
callback(new Error('Not allowed by CORS'))
}
}
};
const configureServer = app => {
app.use(cors(corsOptions));
};
module.exports = configureServer;
这是我的服务器启动文件:
const express = require('express');
const SERVER_CONFIGS = require('./constants/server');
const configureServer = require('./server');
const configureRoutes = require('./routes');
const app = express();
configureServer(app);
configureRoutes(app);
app.listen(SERVER_CONFIGS.PORT, error => {
if (error) throw error;
console.log('Server running on port: ' + SERVER_CONFIGS.PORT);
});
我在本地主机上运行此服务器,但是cors回调中的源始终为'undefined'。例如,当我在浏览器中打开https://dotnetfiddle.net/srx9kM或进行curl调用时。
如何使用cors使其不会阻止本地主机上的请求?
答案 0 :(得分:2)
我阅读了this问题和req.headers.origin is undefined问题,还读了CORS and Origin header!
如果用户来自ssl加密网站,则可能隐藏了来源。
此外:某些浏览器扩展程序从http-request标头中删除了origin和Referer,因此origin属性将为空。
有一个solution通过添加中间件来解决此问题:
app.use(function (req, res, next) {
req.headers.origin = req.headers.origin || req.headers.host;
next();
});
我希望这些会有所帮助。问题处于awaiting more info
状态!