【发布时间】:2021-11-22 22:04:58
【问题描述】:
我在 express 中有一个简单的登录路径:
//login
router.post('/login',async (req,res) => {
try{
const user = await User.findOne({username: req.body.username});
console.log(user);
if (!user) {
return res.status(400).json({
success: false,
message: "username not found"
});
}
const validated = await bcrypt.compare(req.body.password,user.password);
if (!validated) {
console.log('password is wrong')
return res.status(400).json({
success: false,
message: "password not found"
})
}
const {password,...others} = user._doc;
res.status(200).json(others,{
success: true,
});
}
catch(err){
res.status(500).json(err);
}
})
我正在为我的前端和 axios 使用 react 来发出请求:
const handleSubmit = async (e) => {
e.preventDefault();
dispatch({type: 'LOGIN_START'});
try{
const res = await axios.post('http://localhost:5000/api/auth/login',{
username: userRef.current.value, //add the body
password: passwordRef.current.value
})
if (res.data.success) {
dispatch({type: "LOGIN_SUCCESS",payload: res.data})//if everything is fine save it into the localstorage.
}
console.log(res,"something went wrong")
}
catch(err) {
dispatch({type: "LOGIN_FAILURE"})
}
}
现在的问题是,每当我发送 400 状态代码时,它都不会记录我想要查看的响应,我是否想让用户知道发生了什么。
它只是记录:
xhr.js:184 POST http://localhost:5000/api/auth/login 400(错误请求)
我想查看我发回的 json 内容。 我没有找到任何类似的答案。
我错过了什么?
【问题讨论】:
-
你想在状态400上看到的响应,你必须登录catch block
catch(err) {console.log(err.response); dispatch({type: "LOGIN_FAILURE"}) }
标签: node.js reactjs express axios xmlhttprequest