问题
I just started playing with express.js using handlebars.js as my template I wanted to create a delete link, which should be restful and use http verb DELETE instead of GET.
I finally figured out a way to achieve it by creating a link like so below, adding data-method of delete, and then using jquery on client side to intercept my link to use DELETE verb.
My link was:
<a href="/destroy/{{_id}}" data-method="delete">delete</a>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$("a[data-method='delete']").click(function(){
$.ajax({
url: this.getAttribute('href'),
type: 'DELETE'
})
return false
})
</script>
Is this a recommendable way of achieving this in express.js/handlebars.js?, does anyone have a better way of achieving this?, I haven't been able to find something similar to how rails does it within its helper like:
link_to("Destroy", "http://www.example.com", method: :delete)
回答1:
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.
回答2:
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
<form method="POST" action="/destroy/{{_id}}?_method=DELETE">
<button type="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.
来源:https://stackoverflow.com/questions/27058516/create-a-href-link-that-uses-http-delete-verb-in-express-js