reactjs - 反应 Axios 拦截器并创建不起作用
问题描述
我正在尝试将 Axios 与 React 一起使用。由于我的后端服务使用的是 JWT,所以我编写了一个 Axios 请求拦截器,以在每次向服务器发出请求时添加不记名令牌。下面是代码片段。但是我在axiosinstance.post行中遇到了错误。如果使用 axios.post 则拦截器不起作用。你能告诉我什么是错的以及如何解决这个问题吗?
Uncaught TypeError: Cannot read property 'post' of undefined
at request (APIUtils.js:9)
at login (APIUtils.js:23)
at Login.handleSubmit (login.js:36)
at HTMLUnknownElement.callCallback (react-dom.development.js:362)
at Object.invokeGuardedCallbackDev (react-dom.development.js:411)
at invokeGuardedCallback (react-dom.development.js:466)
at invokeGuardedCallbackAndCatchFirstError (react-dom.development.js:480)
at executeDispatch (react-dom.development.js:612)
at executeDispatchesInOrder (react-dom.development.js:637)
at executeDispatchesAndRelease (react-dom.development.js:743)
代码片段 axiosutilis.js
import axios from "axios";
import { API_BASE_URL, ACCESS_TOKEN } from '../constants';
const axiosinstance = axios.create({
timeout: 10000,
params: {} // do not remove this, its added to add params later in the config
});
// Add a request interceptor
axiosinstance.interceptors.request.use(
config => {
if(localStorage.getItem(ACCESS_TOKEN)) {
config.headers.append('Authorization', 'Bearer ' + localStorage.getItem(ACCESS_TOKEN))
}
config.headers['Content-Type'] = 'application/json';
return config;
},
error => {
Promise.reject(error)
});
export default axiosinstance;
APIUtils.js
const request = (options) => {
if(options.method === 'POST'){
return axiosinstance.post(options.url, JSON.stringify(options.data))
.then(response =>
response.json().then(json => {
if(!response.ok) {
return Promise.reject(json);
}
return json;
})
);
}
};
export function login(loginRequest) {
return request({
url: "/api/auth/signin",
method: 'POST',
data: JSON.stringify(loginRequest)
});
}
解决方案
您的解决方案对我来说很好。请找到我的代码沙箱!如果它不起作用,请告诉我!
推荐阅读
- windows-10 - 尝试运行 Microsoft Project 2019 v2012 时出现“内存不足,无法完成操作”
- python - 如何使用 pydicom 在同一系列中保存 DICOM
- android - 科特林。在一个视图模型中获取两个 Firebase 查询
- wpf - 设置属性 Borderthickness 的最大值
- reactjs - 使用 axios 将更多数据与 formData 一起发送到 API
- netsuite - 是否可以在 Netsuite 的 SuiteScript 环境中使用 DOTENV?
- stream - 将视频分析元数据添加到现有的 RTSP 摄像机源
- json - 将 JSON 子对象转换为 Xamarin 表单中的表
- mediawiki - MediaWiki 模板:注意导入不完全正确
- python - Python ABC模块中的abstractclass(metaclass=ABCMeta)和class abstractclass(ABC)有什么区别?