node.js 让快递服务器接受 CORS 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33483675/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 19:27:46  来源:igfitidea点击:

Getting express server to accept CORS request

node.jsexpresscors

提问by runtimeZero

I have my express server running on http://localhost:3000(I call this web-server) I have another application running on localhost:8100 (I call this simply 'app')

我在http://localhost:3000上运行我的快速服务器 (我称之为网络服务器)我在 localhost:8100 上运行了另一个应用程序(我称之为“应用程序”)

When my app makes a call to the webserver I receive the message:

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

"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"

This message shows up in the browser console.

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

I have setup the following options in the middleware of my node webserver

我在节点网络服务器的中间件中设置了以下选项

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

After reading few stackoverfow questions, I also added the following:

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

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

however this does not resolve the issue.

然而这并不能解决问题。

回答by juan david restrepo villada

I use cors and implement it so, it's very simple

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

var cors=require('cors');

var cors=require('cors');

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

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

回答by Thomas Bormans

I personally prefer the corsmodule. The code is really simple:

我个人更喜欢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));

回答by Vsevolod Goloviznin

You also need to allow OPTIONSmethod in the header.

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

I have this middleware for cors:

我有这个用于 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.The error you get is due to the fact of how cross-origin request works. To make a long story short, the browser might first send a pre-flightrequest with method OPTIONSto get allowed origins, headers and methods. So for this request you should return nothing but the Access-Control-*headers. If the pre-flightwent fine, the browser will continue with the original request.

附注。您得到的错误是由于跨域请求的工作原理造成的。长话短说,浏览器可能首先发送一个pre-flight带有方法的请求,OPTIONS以获取允许的来源、标题和方法。所以对于这个请求,你应该只返回Access-Control-*标题。如果pre-flight一切顺利,浏览器将继续执行原始请求。

You can find more information here.

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

回答by runtimeZero

Apparently cors module didn't work.

显然 cors 模块不起作用。

Using the hints given above I used the following code:

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

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

This did the trick.

这成功了。

回答by Louie Almeda

Got the same problem and stumbled for about an hour, the solution was actually simple, just enable CORS for preflight operations

遇到同样的问题,磕磕绊绊了一个小时左右,解决方法其实很简单,只需要开启CORS进行预检操作

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

回答by Thierry

I thought I'd had cracked this one before but once I swapped back from IIS to IIS Express, I started to get the error again!!

我以为我以前已经破解了这个,但是一旦我从 IIS 切换回 IIS Express,我又开始收到错误!!

Started to Google once again and tried numerous suggestions, including the ones above but none of them worked until I found this article from Melvin's Web Stuff - Enable CORS IIS Expresswhich suggested the following:

再次开始使用 Google 并尝试了许多建议,包括上面的建议,但直到我从Melvin 的 Web Stuff - Enable CORS IIS Express 中找到这篇文章后,这些建议都没有奏效,其中提出了以下建议:

Add the following 2 lines to the <customHeaders>section under the <httpProtocol>section:

将以下 2 行添加到该<customHeaders>部分下的<httpProtocol>部分:

<add name="Access-Control-Allow-Origin" value="*" />
<add name="Access-Control-Allow-Headers" value="Content-Type" />

to the applicationhost.config located in:

到位于以下位置的 applicationhost.config:

%HOMEPATH%\Documents\IISExpress\config

The final result should look like this:

最终结果应如下所示:

<httpProtocol>
   <customHeaders>
      <clear />
         <add name="X-Powered-By" value="ASP.NET" />
         <add name="Access-Control-Allow-Origin" value="*" />
         <add name="Access-Control-Allow-Headers" value="Content-Type" />   
   </customHeaders>
   <redirectHeaders>
      <clear />
   </redirectHeaders>
</httpProtocol>

This worked nicely for me but note that I didn't need the above when running in IIS.

这对我来说很好用,但请注意,在 IIS 中运行时我不需要上述内容。