简体   繁体   中英

Django rest framework 401 error with React Axios

Im working on a project with Django rest framework backend and React as frontend. Axios is used for http request and JWT for authentication. I issue im facing is that, after login and getting token django is throwing 401 error for every request. But this issue is resolved if header config is toggled for Axios.

Please find the below codes for your reference and help to resolve.

Thanks in advance.

DRF **settings.py**

 REST_FRAMEWORK = {
  'DEFAULT_AUTHENTICATION_CLASSES': (
      'rest_framework_simplejwt.authentication.JWTAuthentication',
 )
}

SIMPLE_JWT = {
'ACCESS_TOKEN_LIFETIME': timedelta(days=1),
'REFRESH_TOKEN_LIFETIME': timedelta(days=2),
'ROTATE_REFRESH_TOKENS': False,
'BLACKLIST_AFTER_ROTATION': False,
'UPDATE_LAST_LOGIN': True,
}


CORS_ALLOWED_ORIGINS = [
"http://localhost:3000"
]

**axios setup**


const axiosClient = axios.create({
baseURL: import.meta.env.VITE_API_URL,
headers: {
"Content-Type": "application/json",
},
});

export default axiosClient;

const jToken = useSelector((state) => state.authSlice.accessToken);
axiosClient.interceptors.request.use(function (config) {
config.headers.Authorization = `Bearer ${jToken}`;
 return config;
});


**Axios request**

const fetchData = async () => {
try {
  const response = await axiosClient.get(AppContext.managementStudentUri);
  //   console.log(response.data);
  setData(response.data);
  setIsLoading(false);
} catch (error) {
  apiErrorHandler(error);
}
};

But this issue is resolved if header config is toggled for Axios.

The token is used for Authentification so once Login is done and token is generated, it should be sent with every request to identify the use.

But if it's not sent Django throws a 401 Unauthorized Error

https://www.django-rest-framework.org/api-guide/authentication/ https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM