reactjs - 当 HTTP 响应状态为 400 时,我错过了响应 .status,
问题描述
我的问题是当我使用自定义 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
正确获得。
推荐阅读
- javascript - 如何合并具有相同值的 Js 对象?
- avro - Avro 模式演变 - 将原始字段转换为复杂字段
- drools - Drools LHS 如何更新地图
- sql - 在 SQL 中将数据列更改为具有不同根的 JSON
- php - 如何从数据库中获取数据?
- apache - 通过 RewriteEngine 替换 URL 中的子字符串
- javascript - 根据 javascript 或 jquery 中已排序的第一列对第二列进行排序,保持第一排序不变
- react-native - 如何将参数传递到另一个选项卡导航屏幕
- angular - 带有 Angular 11 的 @kolkov/angular-editor 中的项目符号和编号不起作用
- angular - 如何在不重新渲染所有组件树的情况下设置深度嵌套属性?