req.body 在 POST 请求中有效,但在 PUT 请求中无效。

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

req.body working for POST request but not for PUT request

问题

You are encountering an issue where req.body.something is undefined after updating an array in your API. It appears that you expect to get the updated data but only receive the MongoDB default ID. You've mentioned that you've used body-parser and other middleware correctly.

Here are some suggestions:

  1. Ensure Middleware Order: Middleware order is important. Make sure you are using body-parser or similar middleware before your routes are defined. In your server.js, you have commented out body-parser, so you should use express.json() and express.urlencoded() for parsing JSON and form data.

  2. Request Structure: Check the structure of the request you are making in Postman. The request body structure should match the structure expected by your Update function. In this case, it should include an Episodes object with EpisodeNo, EpisodeName, and EpisodeDescription.

  3. Logging: You are logging req.body.EpisodeNo, req.body.EpisodeName, and req.body.EpisodeDescription in your Update function. Ensure that these values are present in the request body when you make the POST request.

  4. Response: The response you posted only includes the MongoDB default ID. Ensure that you are sending back the updated data in your response. You can modify your Update function to include the updated data in the response.

Without seeing the exact request and response data, it's challenging to pinpoint the exact issue. Make sure your request body matches the expected structure, and the data you want to update is being sent correctly in the request. Also, confirm that your Update function is correctly handling and responding with the updated data.

英文:

Actually i am updating an array in my api and after updating the array i am only getting the mongodb default id. It seems that the req.body.something is not defined although the req.body is defined. And i am using all middlewares properly like body-parser

This is the server.jscode

/* eslint-disable no-unused-vars */
/* eslint-disable no-undef */
const mongoose = require('mongoose')
const express = require('express')
const cors = require('cors')
// const bodyParser = require('body-parser')
const userRouters = require('./routes/user.js')
const podcastRouter = require('./routes/pocasts.js')
// const methodOverride = require('method-override')
const port = 8080
const app = express()

// app.use(bodyParser.json())
app.use(express.json())
app.use(express.urlencoded({extended: true}));
// app.use(express.methodOverride());

app.use(cors({
    credentials: true,
}))

//routes
app.use('/',userRouters)
app.use('/api/podcasts' , podcastRouter)

app.post('/api/podcasts',(req,res)=>{
    res.send("This is the api page")
})

app.post('/login',(req,res)=>{
    res.send("This is the login page")
})

app.post('/signup',(req,res)=>{
    res.send("This is the signup page")
    res.json(req.body)
})

const DB = "mongodb+srv://fk28:farhankhan123@cluster0.fq2ibrs.mongodb.net/test"

mongoose.connect(DB , {
    useNewUrlParser:true,
    useUnifiedTopology:true
}).then(()=>{
    console.log("connection successful")
}).catch((err)=>{
    console.log(err)
})

app.listen(port , ()=>{
    console.log("listening to port",port)
})

You can see that i have used bodyparser and other middleware. And also placed them before routers.

This is the update code

const Update =async (req,res)=>{
    const _id = req.params.id
    // const { ...data } = req.body
    const bodycontent = req.body

    try{
        const UpdatedPodcast = await Podcasts.updateOne({
            _id
        },
        {
            $push:{
                Episodes:[{
                    EpisodeNo:bodycontent.EpisodeNo,
                    EpisodeName:bodycontent.EpisodeName,
                    EpisodeDescription:bodycontent.EpisodeDescription
                }]
        }
        },
        {
            upsert:true,
            new:true
        }
        )
        console.log(req.body.EpisodeNo,req.body.EpisodeName,req.body.EpisodeDescription)
        console.log(req.body)
        res.send(UpdatedPodcast)
    }catch(err){
        res.status(500).json({
            message:"Error in updating the data"
        })
    }
}

Here i am consolling the req.body and also req.body.something

This is the consolled output

undefined undefined undefined
{
  Episodes: {
    EpisodeNo: 3,
    EpisodeName: 'All About Cooking',
    EpisodeDescription: 'Cooking is fun'
  }
}

This the api output

{
"_id": "646e2cc2040b492346842b34"
},

I am using Postman to make request

This is the POSTMAN request

{
    
    "Episodes": 
        {
            "EpisodeNo": 3,
            "EpisodeName": "All About Cooking",
            "EpisodeDescription": "Cooking is fun"
        }
    
}

I have used all middlewares but then also getting req.body.something as undefined.
I am expecting where i am only getting default mongodb id i , i should get the updated data too.

答案1

得分: 1

您的EpisodeNo、EpisodeName和EpisodeDescription是嵌套对象属性,因为您在请求中传递了嵌套的JSON。

所以应该像这样获取值:

const { EpisodeNo, EpisodeName, EpisodeDescription } = req.body.Episodes

或者您可以单独传递每个属性,而不是嵌套。

{
    "EpisodeNo": 3,
    "EpisodeName": "All About Cooking",
    "EpisodeDescription": "Cooking is fun"
}
英文:

Your EpisodeNo, EpisodeName, EpisodeDescription is a nested object properties, because you pass in nested JSON in the request.

So get the value like this instead:

const {EpisodeNo, EpisodeName, EpisodeDescription} = req.body.Episodes

Or you can pass in each property without nested.


{
"EpisodeNo": 3,
"EpisodeName": "All About Cooking",
"EpisodeDescription": "Cooking is fun"
}

huangapple
  • 本文由 发表于 2023年5月25日 14:50:00
  • 转载请务必保留本文链接:https://go.coder-hub.com/76329582.html
匿名

发表评论

匿名网友

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

确定