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

时间:2015-03-22 15:45:49

标签: javascript node.js express cors backend

我正在尝试为我的Express.js后端设置CORS。由于我有一个本地和远程版本的前端,我想允许几个URLS访问后端。我试过用#34; *"和var cors = require('cors') app.use(cors())但我得到了

  

凭据时,无法在Access-Control-Allow-Origin中使用通配符   旗帜是真的。

我尝试过使用cors()的动态设置,但没有示例如何将它与Express的路由一起使用。我现在正尝试使用下面的代码创建我自己的白名单检查,但现在我正在

  

否'访问控制 - 允许 - 来源'标题出现在请求的上   资源。起源' http://localhost:5000'因此是不允许的   访问。响应的HTTP状态代码为500。

我做错了什么?

UPDATE:看起来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);

1 个答案:

答案 0 :(得分:2)

这最终归结为拼写/理解错误。我试图使用req.headers.Origin来获取请求来源。事实证明,标题中没有“Origin”,我不得不使用req.headers.origin。下面的代码可以使用,让你使用多个URL作为CORS,它还不能轻易处理像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);