检查 axios 库中是不是返回 404 错误

Posted

技术标签:

【中文标题】检查 axios 库中是不是返回 404 错误【英文标题】:Checking if a 404 error was returned in the axios library检查 axios 库中是否返回 404 错误 【发布时间】:2021-07-06 22:34:36 【问题描述】:

axios 库中,404 错误不会直接返回为res.status,而是作为错误在 catch 中抛出。 我现在的问题是,我可以在 catch 中以某种方式查询错误的编号吗?

.catch(error => 
if(error.status === 404)     
// do something     

或者如何使用axios库来查询是否是404错误?

const handleLogin = () => 
        axios.post('localhost:4000', "email":`$email`, "password":`$password`)
          .then(res => 
            console.log(res);
            console.log(res.data);
            console.log(res.status);
            if(res.status === 200) 
              setValidationNoExist(true);
               history.push(
                pathname: '/app',
                state: 
                  email: email,
                  name: password,
                ,
              )
            
            else if(res.status === 203) 
              setValidationWrong(false);
            
            else if(res.status === 404) 
                setValidationPending(false);
            
             else if(res.status === 204) 
                setValidationNoExist(false);
              
          )
          .catch(error => 
            console.log(error)
            setValidationNoExist(false);
        )
       ;

【问题讨论】:

这能回答你的问题吗? How can I get the status code from an http error in Axios? 【参考方案1】:

https://www.npmjs.com/package/axios#handling-errors

您能否检查 error.response.status 是否在您的 catch 块中为您提供了所需的值。

【讨论】:

以上是关于检查 axios 库中是不是返回 404 错误的主要内容,如果未能解决你的问题,请参考以下文章