可以在浏览器中访问Node/MongoDB中的数据,但不能在Postman中访问-这是CORS问题吗?

mwkjh3gx  于 2023-06-22  发布在  Node.js
关注(0)|答案(1)|浏览(93)

我正在测试Node.js后端,它连接到MongoDB。
Node/MonogoDB连接很好--当我在浏览器中输入http://localhost:3000/stories时,它会显示来自数据库的数据响应。
但在Postman上测试时,没有任何结果:Error: CORS request rejected: http://localhost:3000/stories
下面是控制器:

const { getCollection } = require('./service/DatabaseService')
const { ObjectId } = require('mongodb')

const handleOptionsRequest = async (request, response) => {
    response.status(200).send()
}

const getStory = async (request, response) => {
    const collection = await getCollection("Project", "Collection")
    let data = await collection.find({}).toArray()
    console.log(data)
    return response.status(200).json({
        message: "Successfully retrieved story",
        data: data,
    })
}

module.exports = { getStory, handleOptionsRequest }

和index.js

const { routes } = require('./routes.js')
const express = require('express')
const app = express()
const port = 3000

app.use(express.json())
app.use(express.urlencoded({ extended: true }))

app.use(function (request, response, next) {
  response.header("Access-Control-Allow-Origin", "*")
  response.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept")
  response.header("Access-Control-Allow-Methods", "GET", "OPTIONS")
  next()
})

routes(app)

app.listen(port)

我试着记录变量、请求和对终端的响应。
当Postman将其请求发送到Node时,控制器中的函数运行并将数据从DB记录到终端。
但它不能通过 Postman !
有什么想法吗

k7fdbhmy

k7fdbhmy1#

这是一个cors问题。如果你想允许cors,那么使用npm i cors安装cors包,然后使用app.use(cors())

const express = require('express')
const cors= require('cors');
const app = express();
const port = 3000;

app.use(cors());
app.use(express.json())
app.get('/',(req, res)=>{
// Do something here, send response
});
app.listen(port);

相关问题