【发布时间】:2021-10-02 22:39:39
【问题描述】:
我正在实现一个用户登录系统,但是当我向我的服务器发送请求时,我的服务器正在接收未定义的数据。首先我是通过代理进行的,但是即使在提供完整的 url 之后它也不起作用并且在提交时它也会被重定向到 http://localhost:3000/login 但它应该在成功时被重定向到主页如果它没有授权它会提醒用户。
客户端登录
const loginUser = async (e) => {
// e.preventDefault();
const res = await fetch("http://localhost:8000/login", {
method: "POST",
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email:email,
password:password,
}),
});
const data = await res.json();
console.log("Data",data)
if (data.status === 422 || !data) {
console.log("Invalid cred");
window.alert("Invalid Credentials");
}
if(data.status === 400){
window.alert("wrong password");
}
else{
window.alert("Login Suceesfuuly");
console.log("Login success");
history.push("/");
}
};
在这种情况下,即使数据无效或未正确填写,它也应该显示警报,但它被重定向到 http://localhost:3000/login 并且给了我一些 json 响应,此页面的内容是:
{"error":"pls filled all the field"}
以及服务器端登录功能的代码
服务器端登录
try {
const { email, password } = req.body;
console.log("we got a request", email, password);
if (!email || !password) {
return res.status(422).json({ error: "pls filled all the field" });
}
const userLogin = await User.findOne({
$and: [{ email: email }],
});
if (!userLogin) {
return res.status(422).json({ error: "User is not authorized" });
}
if (userLogin) {
const passwordMatch = await bcrypt.compare(password, userLogin.password);
const token = await userLogin.generateAuthToken();
res.cookie('jwtoken', token, {
expires: new Date(Date.now() + 25892000000),
httpOnly:true
})
if (passwordMatch) {
return res.status(200).json({ message: "login success" });
} else {
return res.status(400).send({ error: "The password is invalid" });
}
}
} catch (err) {
console.log(`Error: ${err}`);
}
每次我从客户端发出请求时,我都会在服务器端得到这个
we got a request undefined undefined
【问题讨论】:
-
你在后端设置bodyparser了吗?
-
打开开发者控制台并检查客户端请求是否有请求体——如果有,那么你的后端有问题。我看到它是 nodejs + express,所以一个想法可能是你还没有设置正文解析器。
标签: html node.js reactjs api fetch-api