如何使用 Node 服务器处理预检 CORS 请求?

问题描述 投票:0回答:1

我已在节点服务器中配置了 COR,如下所示。

var originsWhitelist = [
  'http://localhost:4200'     //this is my front-end url for development

];
var corsOptions = {
  origin: function(origin, callback){
        console.log(origin);
        var isWhitelisted = originsWhitelist.indexOf(origin) !== -1;
        console.log(isWhitelisted);
        callback(null, isWhitelisted);
  },
  credentials:true
}

app.use(cors(corsOptions))

我正在从 Angular 前端发送 json 数据,但在此期间我收到了这样的错误, 选项 http://localhost:30000/api/addProfile 0 ()

我的请求标头是,

Provisional headers are shown
Access-Control-Request-Headers: content-type
Access-Control-Request-Method: POST
Origin: http://localhost:4200
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36

所以,我有其他发布请求,其中我正在发送多部分/从数据,但它工作正常,而此请求发送错误并且响应是未知错误。

node.js cors http-headers preflight
1个回答
0
投票

这应该可以做到:

app.options('*', cors(corsOptions));

您应该阅读该文档:https://github.com/expressjs/cors#enabling-cors-pre-flight

这个问题对我来说也很奇怪,因为浏览器不应该为 POST 请求触发预检。也许我错过了一些关于 CORS 的事情。

© www.soinside.com 2019 - 2024. All rights reserved.