获取Express服务器接受CORS请求

问题描述:

我有我的快递服务器上http://localhost:3000运行(我称之为web服务器) 我有另一个应用程序在本地主机上运行:8100(我把这个简单的“应用”)获取Express服务器接受CORS请求

当我的应用程序打电话给Web服务器我收到消息:

"XMLHTTPReqeust cannot load http://localhost:3000/auth/facebook. Response to preflight request doesn't pass access control check. A wildcard '*' cannot be used in the 'Access-Control-Allow-Origin' when the credentials flag is true. Origin 'http://localhost:81000' is therefore not allowed acecss" 

此消息显示在浏览器控制台中。

我已经安装在我的节点的网络服务器

res.header('Access-Control-Allow-Origin', '*'); 
res.header('Access-Control-Allow-Methods', 'GET,PUT, POST,DELETE'); 

的中间件下列选项读几stackoverfow问题后,我还增加了以下内容:

res.header('Access-Control-Allow-Origin', 'http://localhost:8100'); 

然而,这并不解决问题。

+3

您还需要在'Access-Control-Allow-Methods'中允许'OPTIONS'方法 –

我个人比较喜欢cors模块。代码非常简单:

var whitelist = [ 
    'http://0.0.0.0:3000', 
]; 
var corsOptions = { 
    origin: function(origin, callback){ 
     var originIsWhitelisted = whitelist.indexOf(origin) !== -1; 
     callback(null, originIsWhitelisted); 
    }, 
    credentials: true 
}; 
app.use(cors(corsOptions)); 
+3

我建议使用cors模块,正如托马斯建议的那样,而不是处理标题内容。它很容易设置和使用。它需要30秒来解决一般问题。 – user5026837

您还需要在标头中允许OPTIONS方法。

我有这样的中间件CORS:

module.exports = function (req, res, next) { 
    // CORS headers 
    res.header("Access-Control-Allow-Origin", "YOUR_URL"); // restrict it to the required domain 
    res.header("Access-Control-Allow-Methods", "GET,PUT,POST,DELETE,OPTIONS"); 
    // Set custom headers for CORS 
    res.header("Access-Control-Allow-Headers", "Content-type,Accept,X-Custom-Header"); 

    if (req.method === "OPTIONS") { 
     return res.status(200).end(); 
    } 

    return next(); 
}; 

PS。你得到的错误是由于跨源请求的工作原理。长话短说,浏览器可能会首先发送一个pre-flight请求与方法OPTIONS获得允许的来源,标题和方法。所以对于这个请求,你应该只返回Access-Control-*标题。如果pre-flight没有问题,浏览器将继续处理原始请求。

你可以找到更多的信息here

显然cors模块没有工作。

使用上面我给出的提示,用下面的代码:

if (req.method === "OPTIONS") { 
    res.header('Access-Control-Allow-Origin', req.headers.origin); 
    } else { 
    res.header('Access-Control-Allow-Origin', '*'); 
    } 

这并获得成功。

+1

这应该是最佳答案。 –

得到了同样的问题,偶然发现了大约一个小时,溶液呈其实很简单,只需启用CORS为preflight operations

app.options('*', cors()); // include before other routes 
+1

结合runtimeZero if-else代码,这对我来说非常合适! 更多细节[这里](https://github.com/expressjs/cors#enabling-cors-pre-flight) – vish213

+1

事实上,CORS的处理需要包含在其他路线帮助很多之前。 –

我使用CORS和实现它的话,它是非常简单的

var cors=require('cors');

app.use(cors({origin:true,credentials: true}));