首页 > 解决方案 > 如果状态为 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 内容。我没有找到任何类似的答案。

我错过了什么?

标签: node.jsreactjsexpressaxiosxmlhttprequest

解决方案


Axios 400 Bad request,你可以console.log(err.response)在你的 catch 块中获得一个更易读的对象。

axios错误分为三种类型messagerequestresponse

catch(err) {
     console.log(err.response);
     dispatch({type: "LOGIN_FAILURE"}) 
}

推荐阅读