【问题标题】:Not being able to handle 401 errors无法处理 401 错误
【发布时间】:2020-07-28 23:57:49
【问题描述】:

当我从我的后端发送 res.status(401).send("authentication error") 并尝试在反应前端捕获它时,我无法检查错误的状态。即使错误代码是401,它总是无法通过if语句。我该如何解决这个问题,以便当状态为401时,它会通过那个if语句?

    onSubmit = async (e) => {
        let formData = new FormData();

        formData.append('image', this.state.file);
        try {
            const res = await axios({
                method: 'post',
                url: '/api/search',
                data: formData,
                headers: {'Content-Type': 'multipart/form-data' }
            })
        } catch (err) {
            // authentication required 
            if (err['status'] === 401) {
                console.log('authentication problems');
                this.props.history.push('/');
            };
        }
    }

【问题讨论】:

    标签: reactjs post axios error-code


    【解决方案1】:

    使用err.response.status === 401err['response']['status'] === 401 代替err['status'] === 401

    【讨论】:

    • 但是,当我使用 console.log(JSON.stringify(err)) 时,我没有看到任何名为响应的属性。这是为什么呢?
    猜你喜欢
    • 2015-12-11
    • 2013-10-17
    • 2018-05-18
    • 2018-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-19
    • 2020-07-01
    相关资源
    最近更新 更多