How to enable DELETE query?

I cannot resolve the request DELETEfrom 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:

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

How to include queries DELETE, like tags GET, PUTand POST?

+4
source share
3 answers

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

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

Please note that I have allowed methods, separated by commas inside the same line. The full 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();
});
+10
source

Solved it by simply using the npm cors package and including all the cors requests, just replacing ...

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

with...

app.use(require('cors')());

, magic cors , .

0

One of your headers is incorrectly configured, so instead

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

indicate

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

But you're right, using the npm package is easier.

0
source

Source: https://habr.com/ru/post/1656820/


All Articles