Home > Blockchain >  My req.body object is showing as empty when I submit a PUT request. I am using the method override m
My req.body object is showing as empty when I submit a PUT request. I am using the method override m

Time:08-02

I am trying to update a form using the put method. I am using method override middleware to make my form use a PUT request instead of a POST. when I console log the req.body to see if any information is coming through its empty.

Here is my ejs code:

<form action="/edit/<%= topic._id %>" method="post" >
                    <input type="hidden" name="_method" value="PUT">
                  
                   <input type="submit" value="Make Edit" >
</form>

I removed the input data since its not necassary.

Here is my express PUT method:

router.put('/edit/:id', async (req, res) => {
    let topic =  await Topic.findById(req.params.id)
     topic = await Topic.findOneAndUpdate({_id: req.params.id}, req.body, {
        new: true,
        runValidators: true
     })
     console.log(req.body)
})

I am also using : app.use(express.urlencoded({extended: true})) app.use(express.json())

why am I not able to perform a update? Im confused on why the req.body is empty and not the updated fields in my form when I click the submit button?

CodePudding user response:

I actually forgot to add the "name" attribute to my inputs! I can't believe I forgot that. When working with a form when the request gets sent it grabs those name fields. That's why the payload was empty.

CodePudding user response:

router.put('/edit/:id', (req, res) => {
  Topic.findByIdAndUpdate({_id: req.params.id}, req.body).then( function() {
    Topic.findOne({_id: req.params.id}).then(topics => {
      res.send(topics);
    });
  });
});

Did you try this way?

  • Related