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.
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With