Can access data from Node/MongoDB in browser but not in Postman – is this a CORS issue?

huangapple go评论66阅读模式
英文:

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&#39;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&#39;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&#39;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(&#39;express&#39;)
const cors= require(&#39;cors&#39;);
const app = express();
const port = 3000;

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

huangapple
  • 本文由 发表于 2023年6月21日 23:58:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76525154.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定