Ad

How To Fix XMLHttpRequest Has Been Blocked By CORS Policy

- 1 answer

I have a problem in angular login component when I user NodeJS server REST API to connect database (MongoDB)

Access to XMLHttpRequest at 'http://localhost:3000/users/login' from origin >'http://localhost:4200' has been blocked by CORS policy: The value of the >'Access-Control-Allow-Credentials' header in the response is 'Content-Type' >which must be 'true' when the request's credentials mode is 'include'. The >credentials mode of requests initiated by the XMLHttpRequest is controlled by >the withCredentials attribute.

here is my code in nodejs file (app.js)

var cors = require ('cors');
app.use(cors({
    origin:['http://localhost:4200','http://127.0.0.1:4200'],
    credentials:true
}));

app.use(function (req, res, next) {

  res.header('Access-Control-Allow-Origin', "http://localhost:4200");
  res.header('Access-Control-Allow-Headers', true);
  res.header('Access-Control-Allow-Credentials', 'Content-Type');
  res.header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
  next();
});

here is git log results : https://prnt.sc/o38w12 In addition, register functions still works when I submit

Ad

Answer

credentials: Configures the Access-Control-Allow-Credentials CORS header. Set to true to pass the header, otherwise it is omitted. Not content-type

Can you try changing

res.header('Access-Control-Allow-Credentials', 'Content-Type');

To

res.header('Access-Control-Allow-Credentials', true);
Ad
source: stackoverflow.com
Ad