[英]React Axios interceptor and create not working
我正在嘗試將 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)
});
}
您的解決方案對我來說很好。 請找到我的代碼沙箱! 如果它不起作用,請告訴我!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.