我正在测试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 !
有什么想法吗
1条答案
按热度按时间k7fdbhmy1#
这是一个
cors
问题。如果你想允许cors
,那么使用npm i cors
安装cors包,然后使用app.use(cors())
。