请求的资源上不存在“ Access-Control-Allow-Origin”标头。 NodejS Express

时间:2020-08-04 04:17:19

标签: node.js express

我收到此错误

(index):1 Access to XMLHttpRequest at 'https://example.com/crm/addlead' from origin 'https://abc.examplehosting.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

我也在我的app.js中添加了此代码

app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
    next();
   

});

请提出可能的问题。

2 个答案:

答案 0 :(得分:2)

您需要安装cors CORS

const cors = require('cors')

var corsOptions = {
  origin: '*',
  optionsSuccessStatus: 200 // some legacy browsers like IE11
}
app.use(cors(corsOptions));

答案 1 :(得分:1)

尝试向您的应用添加cors层,

npm install --save cors

// In your server file
var cors = require('cors');
...

app.use(cors());

了解有关cors here

的更多详细信息