Home > Software engineering >  Error on trying to override POST method with PUT (Method Not Allowed)
Error on trying to override POST method with PUT (Method Not Allowed)

Time:05-10

I am experiencing a "Method Not Allowed" issue when trying to override my POST request with PUT (for updating information in my blog). I already installed method override for koa.

HTML:

  <div >
<form action="/messages/edit/<%= message.id %>?_method=PUT" method="POST">
  <label for="title">Message title:</label>
  <input required value="<%= message.title %>" type="text" id="title" name="title" required>
  <label for="snippet">Message snippet:</label>
  <input required value="<%= message.snippet %>" type="text" id="snippet" name="snippet" required>
  <label for="body">Message body:</label>
  <input required value="<%= message.body %>" type="text" id="body" name="body" required>
  <button>Update</button>
</form>
My routs are the following:
  //edit message
  router.get('/messages/edit/:id', async (ctx, next) => {
    const id = ctx.params.id;
    const result = await MessageModel.findById(id)
    await  ctx.render('edit', {
      title: 'Messages',  
      message: result
     })
    });

The code above runs well, but after I click on submit button, "Method Not Allowed" issue occurs instead of running this:

  //update edited message
  router.put('/messages/edit/:id', async (ctx, next) => {
      MessageModel.findByIdAndUpdate(ctx.params.id, ctx.request.body, {new:true}, (err:any, result:any) => {
      })
    return ctx.redirect('/');
});

Please share your thoughts on this issue. Thank you

CodePudding user response:

Make sure you add the following to your app.js (index.js) file.

app.use(methodOverride('_method'));

CodePudding user response:

You can't set the form method to PUT, it's either GET or POST.

to send a PUT request you can use AJAX, via (for instance) the Fetch API

EDIT: my bad, you used the "tunneling" concept mentioned in that solution.

per this documentation, maybe try with

<form method="POST" action="/resource" enctype="application/x-www-form-urlencoded"> 
<input type="hidden" name="_method" value="PUT">
  • Related