yoges nsamy
yoges nsamy

Reputation: 1435

Why use a hidden field with the method-override package in nodejs?

I refer to the last example in the method-override NPM page. A hidden field needs to be set when using either PUT or DELETE. Why is this so when the code also works without the hidden field?

    <!-- enctype must be set to the type you will parse before methodOverride() -->
<form method="POST" action="/resource" enctype="application/x-www-form-urlencoded">
  <input type="hidden" name="_method" value="DELETE">
  <button type="submit">Delete resource</button>
</form>

I've tried the code as below to be working fine without the hidden field:

<form action="/ideas/{{idea.id}}?_method=PUT" method="post">
  {{!-- <input type="hidden" name="_method" value="PUT"> --}}
    <div class="form-group">
      <label for="title">Title</label>
      <input type="text" class="form-control" name="title" value="{{idea.title}}" required>
    </div>
    <div class="form-group">
      <label for="details">Details</label>
      <textarea class="form-control" name="details" required>{{idea.details}}</textarea>
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
  </form>

Update: My back-end code is as below:

const methodOverride = require("method-override");
app.use(methodOverride("_method"));

app.put("/ideas/:id",(req,res) => {
  res.send("PUT");
})

I have the word "PUT" displayed on the browser irregardless of the use of the hidden field.

Upvotes: 0

Views: 338

Answers (1)

jfriend00
jfriend00

Reputation: 707786

When your form puts ?_method=PUT in the action URL for the form, then that takes care of specify the method name and you do not need to put it in a hidden form element. That's why your second form works just fine because it has that in the URL. It appears you can put the method in either the URL or in a hidden form element.

The doc for putting it in the URL is here, but the overall doc is pretty poor for that module so it takes some examination of the code (which is also pretty confusing) to be sure what is going on.


And, also in your server code, you are telling the method-override code to look for the _method key in the URL or form when you do this:

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

Upvotes: 1

Related Questions