【发布时间】:2021-11-06 13:39:17
【问题描述】:
您好,我正在做一个学校项目并卡住了,我收到了一个 cors 错误。我使用了环回地址以及本地主机。我已经设置了标题并安装了 cors。我没有尝试过 IP 地址,但前端是 React 3000,而后端是 Express 3001。谁能看到我做错了什么?我得到了错误....
localhost/:1 从源“http://localhost:3000”获取“http://localhost:3001/users/login”的访问权限已被 CORS 策略阻止:对预检请求的响应未通过访问控制检查:响应中“Access-Control-Allow-Credentials”标头的值为“”,当请求的凭据模式为“包含”时,该值必须为“真”。
这是登录功能。
const login = (e) => {
e.preventDefault();
let username = document.getElementById('loginusername').value;
let password = document.getElementById('loginpassword').value;
const body = `{ "loginusername" : "${username}", "loginpassword": "${password}" }`;
console.log(body);
fetch('http://localhost:3001/users/login', {
method: 'POST',
mode: 'cors',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: body,
}).then((res) => {
return res.json();
}).then((res) => {
if (res.status !== "success") {
alert(`Error 1 : ${res.status}.`)
} else {
alert(`The user ${res.username} has been successfully created.`);
}
document.getElementById('loginusername').value = '';
document.getElementById('loginpassword').value = '';
}).catch((error) => {
alert(`Error 2 : ${error}.`)
})
}
这是 app.js 中的 cors
var cors = require('cors');
app.use(cors({
origin : [ 'http://localhost:3000' , 'http://localhost:3001' ],
methods:["GET" , "POST" , "PUT", "DELETE"],
credential: true
}));
这是后端的登录路径。
router.post('/login', (req, res) => {
let returnResponce = '';
users.findOne({
where:
{
username: `${req.body.loginusername}`
}
}).then((nextThing) => {
if (nextThing !== null) {
if (nextThing.password == req.body.loginpassword) {
if (req.session.viewCount) {
req.session.viewCount += 1;
} else {
req.session.viewCount = 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.setHeader('Access-Control-Allow-Origin', [ 'http://localhost:3000' , 'http://localhost:3001' ] );
res.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
res.setHeader('Access-Control-Allow-Credentials', 'true');
res.write(returnResponce);
res.end();
});
【问题讨论】:
-
这能回答你的问题吗? Allow multiple CORS domain in express js
-
你想要的 cors 中间件配置属性是
credentials。你有credential。见npmjs.com/package/cors#configuration-options。如果您使用的是 cors 中间件(推荐),则不应手动设置Access-Control-Allow-*响应标头 -
另外,你不应该手动创建 JSON。我推荐
const body = JSON.stringify({ loginusername: username, loginpassword: password })
标签: node.js reactjs express authentication cors