node.js - 如果状态为 400,Xhr 不会记录响应
问题描述
我在快递中有一个简单的登录路线:
//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 内容。我没有找到任何类似的答案。
我错过了什么?
解决方案
Axios 400 Bad request
,你可以console.log(err.response)
在你的 catch 块中获得一个更易读的对象。
axios
错误分为三种类型message
:request
和response
。
catch(err) {
console.log(err.response);
dispatch({type: "LOGIN_FAILURE"})
}
推荐阅读
- mysql - Sequelize Migration 服务器连接两个数据库
- javascript - 如何转换我的对象数组以获得此输出?
- azure - Azure Speech to text 演示通过错误。
- python - 我想知道我应该如何填写第二个参数,以免出现 str not callable 错误
- google-chrome - Twilio Video 未在较慢的网络上发布
- wordpress - 使用 WP Rocket 破坏了我的网站 - 未能设置推荐人策略破坏了我的网站
- php - 会话在php中随机过期
- javascript - 如何创建一个可以使用 onclick 更改/恢复部分样式的按钮?
- html - 如何用正则表达式中的其他字符替换
- node.js - PM2 启动 Appname 返回错误无法在 Ubuntu 16 中找到模块