How to fix XMLHttpRequest has been blocked by CORS policy

不问归期 提交于 2020-02-05 06:48:06

问题


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


回答1:


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);


来源:https://stackoverflow.com/questions/56644035/how-to-fix-xmlhttprequest-has-been-blocked-by-cors-policy

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!