【问题标题】:I miss response .status when HTTP response status 400,当 HTTP 响应状态为 400 时,我错过了响应 .status,
【发布时间】:2021-02-23 13:27:35
【问题描述】:

我的问题是当我使用自定义 axios aka axiosInstance 时,我只捕获 res.status == 200,当响应为状态 400 时,我无法获取 res.status 并使用它。 我的配置自定义 axios:

import axios from "axios";
import { API_AUTH } from "./urlConfig";
import store from "../store";
import { authConstants } from "../store/actions/constants";

const token = localStorage.getItem("token") ? localStorage.getItem("token") : sessionStorage.getItem("token");

const axiosInstance = axios.create({
    baseURL: API_AUTH,
    headers: {
        Authorization: token ? `Bearer ${token}` : "",
    },
});

axiosInstance.interceptors.response.use(
    (res) => {
        return res;
    },
    (err) => {
        const { status } = err.response;
        if (status === 400) {
            localStorage.clear();
            store.dispatch({ type: authConstants.LOGOUT_SUCCESS });
        }
        return err;
    }
);
export default axiosInstance;

当我使用 axios 时这段代码

import { authConstants } from "./constants";
import { LOGIN } from "../../helpers/urlConfig";
import authAPI from "../../helpers/authAPI";

export const login = (input) => {
    const { isRemember, ...inputUser } = input;

    return async (dispatch) => {
        dispatch({
            type: authConstants.LOGIN_REQUEST,
        });

        const res = await authAPI.post(LOGIN, {
            ...inputUser,
        });

        if (res.status === 200) {
            //do something OK when status code = 200.
        }
        if (res.status === 400) {
            //can not take res and check res.status
            console.log("res", res);            
        }
    };
};

感谢大家的帮助。

【问题讨论】:

    标签: reactjs axios http-status-codes


    【解决方案1】:

    您可能需要使用catch 处理错误。

    通常我会做这样的事情:

    const res = await authAPI.post(LOGIN, { 
       ...inputUser
    }).catch(error => ({
        status: error.response.status,
        data: error.response.data
    }))
    

    那么您应该能够正确获取res.status

    【讨论】:

    • 感谢您的帮助,它工作正常。干得好兄弟。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 2021-01-20
    • 1970-01-01
    相关资源
    最近更新 更多