首页 > 解决方案 > 使用 axios 时从服务器获取 json 错误响应

问题描述

Axios.post('http://localhost:3001/signup',
        {
            name:name,
            email:email,
            password:password
        })
        .then((res)=>{
            if(res.data){
                M.toast({html: 'Response successfully recorded!'}) //giving the message
            }
            console.log(res);
        })

我正在使用这段代码在我的反应应用程序中将 POST 请求发送到后端服务器,但无法获得服务器给出的 json 错误,我得到了这个:-

xhr.js:177 POST http://localhost:3001/signup 422 (Unprocessable Entity)
Uncaught (in promise) Error: Request failed with status code 422
    at createError (createError.js:16)
    at settle (settle.js:17)
    at XMLHttpRequest.handleLoad (xhr.js:62)

如何获取服务器给出的用于处理前端错误的json错误?

标签: javascriptjsonreactjsaxios

解决方案


您需要使用.catch

Axios.post('http://localhost:3001/signup',
{
    name:name,
    email:email,
    password:password
})
.then((res)=>{
    if(res.data){
        M.toast({html: 'Response successfully recorded!'}) //giving the message
    }
    console.log(res);
}).catch((err) => console.log(err));

.then表示请求成功。

.catch表示请求失败。


推荐阅读