HTTP DELETE verb in Node.JS

2020-07-06 02:43发布

问题:

Do I need to set up any configuration before I can make DELETE requests to a node.js application?

I can make GET, POST or PUT requests, but DELETE requests won't work.

DELETE http://localhost:8081/api/1.0/entry yields undefined from the routing logger, I'm using express to register the routes. But it looks like I can't even resolve the url / verb.

This is how I'm invoking it:

rows.find('a.remove').on('click', function(){
    $.ajax({
        url: '/api/1.0/entry',
        type: 'DELETE'
    }).done(function(res){
        var row = $(this).parentsUntil('tbody');
        row.slideUp();
    });
});

Sample log

GET / 200 18ms  
GET /author/entry 200 10ms  
GET /api/1.0/entry 200 2ms  
GET /api/1.0/entry 200 1ms  
GET /api/1.0/entry 200 1ms  
undefined

回答1:

Hopefully this can help:

  • Enable logging as your first middleware to make sure the request is coming in:

    app.use(express.logger());

  • Use the methodOverride() middleware:

    app.use(express.bodyParser());

    app.use(express.methodOverride()); // looks for DELETE verbs in hidden fields

  • Create a .del() route:

    app.del('/api/1.0/entry', function(req, res, next) { ... });



回答2:

PUT and DELETE values for type setting are not supported by all browsers:

See documentation http://api.jquery.com/jQuery.ajax/

You can use POST type including data:{_method:'delete'} in ajax request:

$.ajax({
    data:{_method:'delete'},
    url: '/api/1.0/entry',
    type: 'POST'
}).done(function(res){
    var row = $(this).parentsUntil('tbody');
    row.slideUp();
});