简体   繁体   中英

Express not recognizing correct request body from Postman on PUT request

I'm working on an extremely simple CRUD backend using Express and MongoDB. It doesn't even have a frontend and I'm just using Postman to verify that each request is working as expected. Here's what my single-page app looks like so far:

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. Here is what I've been trying in Postman after running the server locally:

在此处输入图片说明

在此处输入图片说明

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. Why is the request body from Postman not being recognized for this request?

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. I then used raw json in the Postman client to successfully send PUT requests.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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