英文:
Can access data from Node/MongoDB in browser but not in Postman - is this a CORS issue?
问题
我正在测试一个连接到MongoDB的Node.js后端。
Node/MongoDB连接没问题 - 当我在浏览器中输入`http://localhost:3000/stories`时,它会显示来自数据库的响应数据。
但是在Postman上进行测试时,什么都没有返回:`错误:CORS请求被拒绝:http://localhost:3000/stories`
以下是控制器:
```js
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: "成功检索到故事",
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时,控制器中的函数会运行,并将来自数据库的数据记录到终端中。
但它无法传递给Postman!
有任何想法吗?
<details>
<summary>英文:</summary>
I'm testing a Node.js back end, which connects to MongoDB.
The Node/MonogoDB connection is fine - when I enter `http://localhost:3000/stories` in the browser it shows the response with data from the DB.
But when testing on Postman, nothing comes back: `Error: CORS request rejected: http://localhost:3000/stories`
Here's the controller:
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 }
and 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)
I tried logging the variables, request and response to the terminal.
When Postman is sending its request to Node, the function in the controller runs and does log the data from the DB to the terminal.
But it can't get through to Postman!
Any ideas?
</details>
# 答案1
**得分**: 0
这是一个`cors`问题。如果您想允许`cors`,请使用`npm i cors`安装cors包,然后使用`app.use(cors())`。以下是您的代码的翻译:
```javascript
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) => {
// 在这里执行某些操作,发送响应
});
app.listen(port);
英文:
It is a cors
issue. If you want to allow cors
then install cors package using npm i cors
and then use 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论