如何修复 XMLHttpRequest 已被 CORS 策略阻止

min*_*yen 3 node.js cors angular

当我使用 NodeJS 服务器 REST API 连接数据库(MongoDB)时,角度登录组件出现问题

从源 >' http://localhost:4200 ' 访问位于' http://localhost: 3000/users/login'的 XMLHttpRequest已被 CORS 策略阻止: >'Access-Control-Allow-Credentials' 的值响应中的标头是“Content-Type”>当请求的凭据模式为“include”时,该标头必须为“true”。XMLHttpRequest发起的请求的credentials模式由withCredentials属性控制。

这是我在nodejs文件(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();
});
Run Code Online (Sandbox Code Playgroud)

这是 git log 结果: https: //prnt.sc/o38w12 另外,当我提交时,注册功能仍然有效

Mad*_*yil 5

credential:配置 Access-Control-Allow-Credentials CORS 标头。设置为 true 以传递标头,否则省略。不是内容类型

你可以尝试改变吗

res.header('Access-Control-Allow-Credentials', 'Content-Type');
Run Code Online (Sandbox Code Playgroud)

res.header('Access-Control-Allow-Credentials', true);
Run Code Online (Sandbox Code Playgroud)