为什么我的Express.js后端的CORS设置不起作用?

我正在为我的Express.js后端设置CORS。 由于我有一个本地和远程版本的前端我想允许一些URLS访问到后端。 我曾尝试使用“*”和var cors = require('cors') app.use(cors())但我得到

当凭证标志为真时,不能在Access-Control-Allow-Origin中使用通配符。

我曾尝试使用cors()的dynamic设置,但没有示例如何使用Express的路线。 我现在试图创build我自己的白名单检查下面的代码,但现在我越来越

请求的资源上没有“Access-Control-Allow-Origin”标题。 原因' http:// localhost:5000 '因此不被允许访问。 该响应具有HTTP状态码500。

我究竟做错了什么?

更新:它看起来像if语句阻止添加标题,所以我试图删除它,看看res.header('Access-Control-Allow-Origin', req.get("origin")); 现在正在给我

凭证标志是'true',但是'Access-Control-Allow-Credentials'标头是''。 允许凭证必须是“真实的”。

 var whiteList = { "http://localhost:5000": true, "https://example-url.herokuapp.com": true }; var allowCrossDomain = function(req, res, next) { if(whiteList[req.get('Origin')]){ res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Origin', req.get('Origin')); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Origin, Accept'); next(); } }; app.use(allowCrossDomain); 

这最终归结为拼写/理解错误。 我试图通过使用req.headers.Origin来获取请求源。 原来req.headers.origin没有'Origin',我不得不使用req.headers.origin 。 下面的代码将工作,并让你使用CORS的多个URL,它还不能轻易处理像http://localhost:5000/route或提供的来源不在列表中的情况。

 var whiteList = { "http://localhost:5000": true, "https://example-url.herokuapp.com": true }; var allowCrossDomain = function(req, res, next) { if(whiteList[req.headers.origin]){ res.header('Access-Control-Allow-Credentials', true); res.header('Access-Control-Allow-Origin', req.headers.origin); res.header('Access-Control-Allow-Methods', 'GET,PUT,POST,DELETE,OPTIONS'); res.header('Access-Control-Allow-Headers', 'Content-Type, Authorization, Content-Length, X-Requested-With, Origin, Accept'); next(); } }; app.use(allowCrossDomain);