Javascript 使用axios时从服务器获取json错误响应

Javascript 使用axios时从服务器获取json错误响应,javascript,json,reactjs,axios,Javascript,Json,Reactjs,Axios,我使用这段代码将POST请求发送到我的react应用程序中的后端服务器,但无法获得服务器给出的json错误,我得到以下信息:- Axios.post('http://localhost:3001/signup', { name:name, email:email, password:password }) .then((res)=>{ if(res

我使用这段代码将POST请求发送到我的react应用程序中的后端服务器,但无法获得服务器给出的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);
        })

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

您需要使用
。catch

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)
。那么
表示请求成功

.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));