gpt4 book ai didi

node.js - 使用Postman时如何解决nodejs中的CORS错误?

转载 作者:行者123 更新时间:2023-12-05 01:34:28 31 4
gpt4 key购买 nike

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.

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?

CORS 错误:由于 CORS 政策,请求已被阻止

最佳答案

您是否尝试过 Express 的 CORS 包?这是一个简单的设置:

npm i cors

然后只需在您的应用中使用它(这会启用ALL CORS 请求):

app.use(cors());

Docs

也回答了here .

关于node.js - 使用Postman时如何解决nodejs中的CORS错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63645176/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com