This question already has answers here:
How can I get the status code from an http error in Axios?
                                
                                    (7个答案)
                                
                        
                                在8个月前关闭。
            
                    
我正在建立一个认证项目。我不确定如何显示错误消息,以便可以在屏幕上打印它们。例如,如果电子邮件地址已经注册,我如何得到该错误。使用邮递员进行测试时,我可以看到错误消息,但不确定如何使用axios。以下是用户输入已经注册的电子邮件时的代码。我如何访问该消息

User.findOne({ email }).then(user => {
    if (user)
        return res.status(400).json({ msg: "Email already in use" });
});

最佳答案

发生的情况是,当服务器返回状态代码(例如400)时,它最终作为客户端代码(执行请求的地方)中的异常结束。有两种不同的处理方法,但是最简单的方法是执行try/catch

这是他们在GitHub上建议的示例:

/*
 * Handling Errors using async/await
 * Has to be used inside an async function
 */
try {
    const response = await axios.get('https://your.site/api/v1/bla/ble/bli');
    // Success 🎉
    console.log(response);
} catch (error) {
    // Error 😨
    if (error.response) {
        /*
         * The request was made and the server responded with a
         * status code that falls out of the range of 2xx
         */
        console.log(error.response.data);
        console.log(error.response.status);
        console.log(error.response.headers);
    } else if (error.request) {
        /*
         * The request was made but no response was received, `error.request`
         * is an instance of XMLHttpRequest in the browser and an instance
         * of http.ClientRequest in Node.js
         */
        console.log(error.request);
    } else {
        // Something happened in setting up the request and triggered an Error
        console.log('Error', error.message);
    }
    console.log(error);
}


他们还有更多示例here。在其他一些HttpClient中,他们可以选择始终返回完整的http响应。我在Axios上看不到该选项,但是它可能只是隐藏在他们的文档中。

10-05 20:37
查看更多