简体   繁体   English

Express无法识别来自Postman的正确请求正文

[英]Express not recognizing correct request body from Postman on PUT request

I'm working on an extremely simple CRUD backend using Express and MongoDB. 我正在使用Express和MongoDB开发极其简单的CRUD后端。 It doesn't even have a frontend and I'm just using Postman to verify that each request is working as expected. 它甚至没有前端,我只是使用Postman来验证每个请求是否按预期工作。 Here's what my single-page app looks like so far: 到目前为止,这是我的单页应用程序的外观:

server.js server.js

const express = require('express')
const bodyParser = require('body-parser')
const MongoClient = require('mongodb').MongoClient

let ObjectId = require('mongodb').ObjectId;

const app = express()
const uri = 'mongodb+srv://<USER>:<PW>@<REDACTED>.mongodb.net/test?retryWrites=true'

let db

MongoClient.connect(uri, { useNewUrlParser: true }, (err, client) => {
  if (err) return console.log(err)
  db = client.db(<COLLECTION_NAME>)
    app.listen(3000, () => {
      console.log('Listening on port 3000')
    })
})

app.put('/todo', (req, res) => {
   db.collection('todo').updateOne({_id: 
      ObjectId(req.body.id)}, {
       $set: {item: req.body.value}
   }, (err, result) => {
        if (err) return console.log(err)
        res.send('Todo updated')
   })
})

I've already populated my cluster's collection in MongoDB Atlas using a POST request (not shown) that works. 我已经使用有效的POST请求(未显示)在MongoDB Atlas中填充了集群的集合。 Here is what I've been trying in Postman after running the server locally: 这是在本地运行服务器后在Postman中一直尝试的操作:

在此处输入图片说明

在此处输入图片说明

The id of the existing Todo is well-defined in the Atlas cluster, but when I log the value of req.body.value in the first line of the callback function of the PUT request in server.js, it's showing the existing value that's in the Todo in that cluster, not what's actually being supplied via Postman. 现有Todo的ID在Atlas集群中定义明确,但是当我在server.js中PUT请求的回调函数的第一行中记录req.body.value的值时,它显示的是在该集群中的Todo中,而不是通过邮递员实际提供的东西。 Why is the request body from Postman not being recognized for this request? 为什么无法识别来自Postman的请求正文?

This post was helpful to figuring out what was wrong. 这篇文章有助于找出问题所在。 I needed to import the bodyParser.json() middleware and include it in the PUT request. 我需要导入bodyParser.json()中间件并将其包含在PUT请求中。 I then used raw json in the Postman client to successfully send PUT requests. 然后,我在Postman客户端中使用了原始json来成功发送PUT请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM