【问题标题】: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);
        })
       };

【问题讨论】:

标签: reactjs api axios


【解决方案1】:

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

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

【讨论】:

    猜你喜欢
    • 2011-08-24
    • 1970-01-01
    • 2021-11-05
    • 2013-12-06
    • 1970-01-01
    • 2019-11-27
    • 2019-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多