我正在尝试比较密码以登录用户,但是我不断收到“此请求无响应。”
这是我的张贴路线。
router.route("/login/:username1").post(async (req, res) => {
const userexist = User.find(username=>userexist.username=req.body.username1)
if(userexist == null)
{
return res.status(400).json("Cannot find user");
}
try
{
if(await bcrypt.compare(req.body.password, userexist.password))
{
res.json("success");
}
else
{
res.json("Not Allowed");
}
} catch {
res.status(500).json();
}
});
这是我登录页面上的发布方法。
onSubmit(e) {
e.preventDefault();
const isValid = this.validate();
const username1=this.state.username;
if (isValid) {
const user = {
username: this.state.username,
password: this.state.password,
};
axios
.post("http://localhost:5000/users/login/"+ username1, user)
.then((res) => console.log(res.data));
this.setState(initialState);
}
}
进行一些更正,看看你怎么走:
axios.post("http://localhost:5000/users/login/"+ username1, user)
find
功能进行校正router.route("/login/:username1").post(async (req, res) => {
const userexist = await User.find(user=>user.username==req.body.username) //<---- make correction to find method ... use await and use correct req body object i.e. username not username1
if(userexist == null)
{
return res.status(400).json("Cannot find user");
}
try
{
if(await bcrypt.compare(req.body.password, userexist.password))
{
res.send("success"); //<----- as best practice, while sending strings just use res.send('success')... res.json is not reqd
}
else
{
res.send("Not Allowed"); //<----- for strings, it is better to use res.send instead of res.json
}
} catch {
res.status(500).json(); //<----- remember to pass meaningful error message back to client
}
});