Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to send a put request from html form in express and node

I have a form for editing an object and I want to handle it properly using express 3.x with node.js

edit item route: /item/edit shows a form for editing the object.

I figure I have three options:

1) place a hidden field with a value of "edit" so I can handle it in express properly This is a little more work because I have to handle it in app.post('/item', routes.item.post); which also will handle new creations as well as updates.

2) only submit the edit form with jQuery.ajax() put call. This allows me to use app.put('/item', routes.item.put);

3) send a post request to /item/edit instead of /item to handle the update/edit post will only be used for updating at /item/edit: app.post('/item/edit', routes.item.edit.post);

Solution #2 is the only one that is intuitive and obvious when looking at the code in app.js and follows standard convention for CRUD. But if javascript is not enabled for some reason, they cannot edit their object.

like image 634
chovy Avatar asked Dec 07 '22 11:12

chovy


2 Answers

http://www.senchalabs.org/connect/middleware-methodOverride.html

express:

app.use(express.bodyParser())
app.use(express.methodOverride())

your html form:

<form method="POST">
  <input type="hidden" name="_method" value="put">
</form>
like image 92
Jonathan Ong Avatar answered Dec 11 '22 07:12

Jonathan Ong


For anyone just recently having this problem here is the updated syntax that worked for me. It might be different when you read this so if this doesn't work just check the method-override instructions. But using method-override 2.3.10 with Express 4.13.4 the following should work.

<form method="POST" action="/edit-post/<post.id>?_method=PUT">
   .....
  <button type="submit">Update Post</button>
</form>
like image 23
mikeym Avatar answered Dec 11 '22 08:12

mikeym