I am trying to use Axios along with React. Since my backend service is using JWT I wrote an Axios request interceptor to add the bearer token every time there is a request made to the server. Below is the code snippet. But I am getting below error in the line axiosinstance.post . If is use axios.post then the interceptor is not working. Could you please let me know what is wrong and how to resolve the issue?
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)
Code snippets 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)
});
}
Your solution works fine for me. Please find my code sandbox! In case it doesn't work let me know!
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.