HTTP DELETE verb in Node.JS

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

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 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) { ... });

Solution 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();
});

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply