in windows 10 , i'm using react-router-dom 5.2.0 and react-redux 7.2.5 and react 17.0.2. and axios 0.21.4 and WebStorm 2023.1.3 IDE.
Consider 1 - axiosInstanse.js:
import jwt_decode from 'jwt-decode';
import dayjs from 'dayjs';
import axios from 'axios';
import {updateAccessToken} from '../actions/userActions';
const baseURL = 'http://127.0.0.1:8000';
const axiosInstance = (userInfo , dispatch) => {
const instance = axios.create({
'mode': 'cors',
baseURL,
headers: {
'Content-Type': 'application/json',
Authorization:`Bearer ${userInfo?.access}`,
}
});
instance.interceptors.request.use(async req=> {
try {
const user = jwt_decode(userInfo.access);
const isExpired = dayjs.unix(user.exp).diff(dayjs()) < 5000;
if (!(isExpired)) {
return req
}
const response = await axios.post(
'/api/v1/users/token/refresh/' , {refresh:userInfo.refresh},
);
dispatch(updateAccessToken(response.data))
req.headers.Authorization = `Bearer ${response.data.access}`;
return req;
} catch (error) {
console.log(error)
}
});
return instance
}
export default axiosInstance;
Consider 2 - userActions.js:
export const userFurtherInformationAction = (image, gender) => async (dispatch, getState) => {
try {
dispatch({ //USER FURTHER INFORMATION REQUEST
type: USER_FURTHER_INFORMATION_REQUEST,
});
const {userLogin: {userInfo}} = getState();
const formData = new FormData();
const image_url = URL.createObjectURL(image)
formData.append('userPicture', image);
formData.append('sex', gender);
// var object = {};
// formData.forEach(function(value, key){
// object[key] = value;
// });
// var json = JSON.stringify(formData);
// const config = {
// 'mode': 'cors', headers: { //
// 'Content-type': 'multipart/form-data', 'Authorization': `Bearer ${userInfo.token}`
// }
// }
const authRequestAxios = axiosInstance(userInfo,dispatch);
const {data} = await authRequestAxios.post('/api/v1/users/complete_user_further_info/', formData);
dispatch({ //USER FURTHER INFORMATION SUCCESS
type: USER_FURTHER_INFORMATION_SUCCESS, payload: data,
});
localStorage.setItem('userInfo', JSON.stringify(data));
} catch (error) {
dispatch({ // USER FURTHER INFORMATION FAILED
type: USER_FURTHER_INFORMATION_FAILED,
payload: error.response && error.response.data.detail ? error.response.data.detail : error.message,
});
}
}
i expect to upload picutre --> but in my frontend -> reactjs -> axios raise error [11/Nov/2023 12:55:36] "POST /api/v1/users/token/refresh/ HTTP/1.1" 401 65
this error raise after making axiosInstance arrow function ... i guess error is at file --> axiosInstance.js