Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to enable DELETE request?

Tags:

cors

express

I'm not able to allow the DELETE request from my API server due to CORS.

server.js

// enable CORS
app.use(function (req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Methods", "GET", "PUT", "POST", "DELETE", "OPTIONS");
    res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
    next();
});

I get a console error saying:

XMLHttpRequest cannot load http://localhost:8080/api/users/57f5036645c04700128d4ee0. Method DELETE is not allowed by Access-Control-Allow-Methods in preflight response

How can I enable DELETE requests, just like GET, PUT, and POST requests?

like image 945
Anubhav Dhawan Avatar asked Oct 05 '16 14:10

Anubhav Dhawan


1 Answers

I solved it without adding new packages, just added this line

res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");

Notice that i have my allowed methods separated by commas inside one string. The complete function looks like this:

app.use(function (req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST, DELETE");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept, Authorization");
  next();
});
like image 79
Jorge Junior Arteaga Carvalho Avatar answered Oct 14 '22 14:10

Jorge Junior Arteaga Carvalho