简体   繁体   English

使用Postman时如何解决nodejs中的CORS错误?

[英]How to solve CORS error in nodejs while using Postman?

I created a REST Api using nodejs and mongodb and i wanted to test it in postman but while doing so I am getting a CORS error.我使用 nodejs 和 mongodb 创建了一个 REST Api 并且我想在 postman 中测试它但是在这样做时我收到了 CORS 错误。

var express = require('express');
var log = require('morgan')('dev');
var bodyParser = require('body-parser');

var properties = require('./config/properties');
var db = require('./config/database.js');
//hero routes
var herosRoutes = require('./api/heros/heros.routes');
var app = express();

//configure bodyparser
var bodyParserJSON = bodyParser.json();
var bodyParserURLEncoded = bodyParser.urlencoded({extended:true});

//initialise express router
var router = express.Router();

// call the database connectivity function
db.mongoc();

// configure app.use()
app.use(log);
app.use(bodyParserJSON);
app.use(bodyParserURLEncoded);

// Error handling
app.use(function(req, res, next) {
    res.setHeader("Access-Control-Allow-Origin", "*");
     res.setHeader("Access-Control-Allow-Credentials", "true");
     res.setHeader("Access-Control-Allow-Methods", "GET,HEAD,OPTIONS,POST,PUT");
     res.setHeader("Access-Control-Allow-Headers", "Access-Control-Allow-Origin,Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Access-Control-Request-Headers,Authorization");
   next();
 });

// use express router
app.use('/api',router);
//call heros routing
herosRoutes.hero(router);

// intialise server
app.listen(properties.PORT, (req, res) => {
    console.log(`Server is running on ${properties.PORT} port.`);
})

Whenever i make any create or get request, i get this CORS error in postman. How to solve this?每当我发出任何创建或获取请求时,我都会在 postman 中收到此 CORS 错误。如何解决这个问题?

CORS Error: The request has been blocked because of the CORS policy CORS 错误:由于 CORS 策略,请求已被阻止

if someone is still having this issue, Postman doesn't provide an origin when calling the API, so when we have restricted CORS policy an error is generated saying Error: Not allowed by CORS .如果有人仍然遇到此问题,Postman 在调用 API 时不提供来源,因此当我们限制 CORS 策略时,会生成一条错误消息Error: Not allowed by CORS

Sample code for bypassing this issue is this:绕过这个问题的示例代码是这样的:

const whitelist = ['https://localhost:3001']
const corsOptions = {
 origin: function (origin, callback) {
    if(!origin){//for bypassing postman req with  no origin
      return callback(null, true);
    }
    if (whitelist.indexOf(origin) !== -1) {
      callback(null, true);
    } else {
      callback(new Error('Not allowed by CORS'))
    }
  }
}
app.use(cors(corsOptions));

Have you tried the CORS package from Express?您是否尝试过 Express 的 CORS 包? It's a simple setup:这是一个简单的设置:

npm i cors

Then just use it in your app (this enables ALL CORS requests):然后只需在您的应用程序中使用它(这将启用所有CORS 请求):

app.use(cors());

Docs文档

Also answered here .也在这里回答。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何解决独立于 CORS 中间件的 NodeJS 中的 CORS 错误 - How to solve CORS error in NodeJS independent of CORS middleware 如何解决 HTTP header 错误,而状态 200 ok 显示在 API 测试中使用 Z03D476861AFDFA88141? - How to solve HTTP header error, while status 200 ok shows in API testing using postman? 在使用 postman 测试基本 Nodejs CRUD API 时,出现错误“无法发布”。 如何解决这个问题? - While testing basic Nodejs CRUD API using postman, it gives error 'Cannot Post'. How to resolve this issue? 如何解决错误 CORS? 模式:'无cors' - How to solve the error CORS ? mode: 'no-cors' 使用假API时出现CORS错误怎么解决? - How to solve CORS error when using fake API? 与React,Axios,Express一起使用时如何解决CORS错误? - How to solve CORS error when using with React, Axios, Express? 如何解决 socket.io laravel 和 nodejs 信号应用中的 cors 错误 - How to solve cors error in socket.io laravel and nodejs signalling app 在nodejs中使用twitter API时如何解决“被CORS策略阻止”? - How to solve “Getting blocked by CORS policy” when using twitter API in nodejs? 如何解决错误:Postman 中的套接字挂起 - How to solve Error: Socket hang up in Postman 在反应中使用 Axios 时如何解决错误 - how to solve error while using Axios in react
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM