当我使用 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 另外,当我提交时,注册功能仍然有效
我尝试通过邮递员创建 post 方法,但邮递员无法读取请求正文,这是我在索引文件上的代码
app.post('/users', async (req, res) => {
const addUser = new User(req.body)
console.log(req.body)
try {
await addUser.save()
res.status(201).send(addUser)
} catch (e) {
res.status(400).send(e)
}
})
Run Code Online (Sandbox Code Playgroud)
这是我使用邮递员时的捕获
这是终端
http://prntscr.com/qvdvpj的结果