HTTP DELETE verb in Node.JS
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();
});
bevacqua
Principal Software Engineer at Elastic, helping lead the Elastic Cloud UI team. ● Pre-IPO employee at Elastic, helping drive key initiatives in Elastic Cloud ● Authored 3 books on JavaScript/Node.js application architecture ● Organized first ever Node.js conference in Buenos Aires (NodeConf Argentina) ● Author dragula drag & drop library (20k stars) and prolific open source contributor ● Wrote my own MVC frameworks, clones of async, jQuery, Markdown parsers, and more (purely as a way of learning) ● Grew newsletter on JavaScript to 17k subscribers (Pony Foo Weekly) ● 40k karma on StackOverflow 😅 ● Avid reader Published author of several software development books: Mastering Modular JavaScript (O'Reilly, 2018), Practical Modern JavaScript (O'Reilly, 2017), and JavaScript Application Design (Manning, 2015). Nicolás has vast experience in tackling challenging technical problems, as well as in helping manage teams, driving technical innovation, collaborating across areas, and sharing his applied learning.
Updated on July 20, 2022Comments
-
bevacqua almost 2 years
Do I need to set up any configuration before I can make DELETE requests to a node.js application?
I can make
GET
,POST
orPUT
requests, butDELETE
requests won't work.DELETE http://localhost:8081/api/1.0/entry
yieldsundefined
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