node.js - 如何修复 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 另外,注册功能在我提交时仍然有效
解决方案
credentials:配置 Access-Control-Allow-Credentials CORS 标头。设置为 true 以传递标头,否则省略。不是内容类型
你能尝试改变吗
res.header('Access-Control-Allow-Credentials', 'Content-Type');
到
res.header('Access-Control-Allow-Credentials', true);
推荐阅读
- javascript - 如何计算 div 标签内的文本行数
- python - 如何检查某人是否有管理员权限 on_message discord.py
- mysql - 哪个 AWS 服务用于我的大型 MySQL 表?
- sql - 如何使用正则表达式作为 CSV 分隔符创建将 CSV 值转换为表格的函数?
- c - 尝试查找复数的绝对值时输出错误,始终为 1
- python - 为任何 n 值扩展 (x+y)**n 二项式
- logstash - 如何在 Logstash 中将 JSON 对象转换为 STRING?
- .net - Blazor 中的 RazorComponent 多次包含在同一页面共享代码中
- c# - 在 VS10 .NET 表单中获取自定义控件的 IDesignerHost 时出现问题
- reactjs - 在 React 应用程序上运行到“npm-start”时出错