问题描述
我的问题是当我使用自定义 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);
}
};
};
感谢所有帮助。
解决方法
您可能需要使用 catch
处理错误。
通常我会这样做:
const res = await authAPI.post(LOGIN,{
...inputUser
}).catch(error => ({
status: error.response.status,data: error.response.data
}))
那么您应该能够正确获取 res.status
。