skip to Main Content

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" class="formCard card">
                    <input type="hidden" name="_method" value="PUT">
                  
                   <input type="submit" value="Make Edit" class="btn btn-dark">
</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?

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search