已设置Access-Control-Allow-Credentials为true仍触发CORS错误如何解决?
问题根因及修复方案
1. 核心错误:CORS配置参数拼写错误
你在app.js中调用cors中间件时,配置项拼写错误:正确参数名为credentials,你写的是credential(少了末尾的s),这直接导致预检请求返回的Access-Control-Allow-Credentials头为空,完全匹配你收到的报错提示。
修正后的app.js配置:
var cors = require('cors'); app.use(cors({ origin : [ 'http://localhost:3000' , 'http://localhost:3001' ], methods:["GET" , "POST" , "PUT", "DELETE"], credentials: true // 修正拼写,添加末尾的s }));
2. 异步逻辑顺序错误
后端登录路由中,users.findOne是异步数据库查询操作,你当前把res.write、res.end等响应逻辑写在then回调外部,会导致数据库查询还未完成,就直接返回了空的响应内容,同时也可能打断CORS头的正常设置。
同时你已经全局配置了cors中间件,不需要在路由中重复手动设置CORS相关响应头,重复设置会引发规则冲突。
修正后的登录路由代码:
router.post('/login', async (req, res) => { let returnResponce = ''; try { const nextThing = await users.findOne({ where: { username: req.body.loginusername } }); if (nextThing !== null) { if (nextThing.password == req.body.loginpassword) { req.session.viewCount = req.session.viewCount ? req.session.viewCount + 1 : 1; req.session.authenticated = "true"; req.session.username = req.body.loginusername; returnResponce = `{ "status" : "Logged In" }`; } else { returnResponce = `{ "status" : "Wrong password." }`; } } else { returnResponce = `{ "status" : "Wrong username." }`; } res.write(returnResponce); res.end(); } catch (err) { res.status(500).write(`{"status": "server error"}`); res.end(); } });
3. 可选优化:前端请求体构造优化
你当前手动拼接JSON字符串的方式容易因为用户输入特殊字符(比如双引号)导致JSON格式错误,建议替换为JSON.stringify方法:
// 替换原来的手动拼接JSON字符串代码 const body = JSON.stringify({ loginusername: username, loginpassword: password });
内容的提问来源于stack exchange,提问作者Harrison
相关产品推荐
相关产品推荐

