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