首页 > 解决方案 > 如何修复 XMLHttpRequest 已被 CORS 策略阻止

问题描述

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

从源>“ http://localhost:4200 ”访问“ http://localhost:3000/users/login ”处的 XMLHttpRequest已被 CORS 策略阻止:>“Access-Control-Allow-Credentials”的值响应中的标头是“Content-Type”>当请求的凭据模式为“包含”时,它必须为“真”。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();
});

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

标签: node.jsangularcors

解决方案


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

你能尝试改变吗

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

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

推荐阅读