Create A Href Link That Uses Http Delete Verb In Express.js
Solution 1:
Thanks @tikider I did more research based on your suggestion and came across a middleware called method-override (https://github.com/expressjs/method-override) Since I wanted to handle DELETE your suggestion was quite complete since forms can't send DELETE
This is how I solved it, first I npm installed method-override:
sudo npm install method-override --save
Attached it to my app middleware handler:
// override with POST having ?_method=DELETE
app.use(methodOverride('_method'));
Then my view I set my delete buttons as
<formmethod="POST"action="/destroy/{{_id}}?_method=DELETE"><buttontype="submit">Delete</button></form>
Now every time I click delete it is changed by method-override to DELETE and caught using a middleware like so within my app:
app.delete('/destroy/:id', function(req, res) {
//...
}
As I am using handlebars template I can then add it as a helper method.
Solution 2:
In your case Rails creates a form
and sets its method to the one you provided:
method: symbol of HTTP verb - This modifier will dynamically create an HTML form and immediately submit the form for processing using the HTTP verb specified. link_to in Rails Doc
your can implement your own in javascript:
var link_to = function (text, href, method) {
return'<form action="' + href + '" method="' + method + '" ><button>'+ text + '</button></form>'
}
you can use css to style this button as a normal link.
Post a Comment for "Create A Href Link That Uses Http Delete Verb In Express.js"