让express server接受CORS请求

run*_*ero 19 node.js cors express

我的快速服务器运行在http:// localhost:3000 (我称之为web服务器)我有另一个应用程序在localhost上运行:8100(我称之为'app')

当我的应用程序拨打网络服务器时,我会收到以下消息:

"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"
Run Code Online (Sandbox Code Playgroud)

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

我在节点webserver的中间件中设置了以下选项

res.header('Access-Control-Allow-Origin', '*');
res.header('Access-Control-Allow-Methods', 'GET,PUT, POST,DELETE');
Run Code Online (Sandbox Code Playgroud)

在阅读了几个stackoverfow问题后,我还添加了以下内容:

 res.header('Access-Control-Allow-Origin', 'http://localhost:8100');
Run Code Online (Sandbox Code Playgroud)

但这并不能解决问题.

小智 18

我使用cors并实现它,这很简单

var cors=require('cors');

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


Tho*_*ans 17

我个人更喜欢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));
Run Code Online (Sandbox Code Playgroud)

  • 我建议像Thomas建议的那样使用cors模块,而不是处理头文件.它易于设置和使用.它可以解决一般问题30秒. (3认同)

Vse*_*nin 15

您还需要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();
};
Run Code Online (Sandbox Code Playgroud)

PS.您得到的错误是由于跨源请求的工作原理.长话短说,浏览器可能首先发送一个pre-flight请求,其中包含OPTIONS获取允许的起源,标题和方法的方法.因此,对于此请求,您应该只返回Access-Control-*标题.如果运行pre-flight正常,浏览器将继续原始请求.

您可以在此处找到更多信息.

  • 谢谢你!`if (req.method === "OPTIONS")` 是我所缺少的 (6认同)

run*_*ero 8

显然cors模块不起作用.

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

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

这样做了.


Lou*_*eda 7

遇到了同样的问题并且发现了大约一个小时,解决方案实际上很简单,只需启用CORS进行预检操作

app.options('*', cors()); // include before other routes
Run Code Online (Sandbox Code Playgroud)