Hi All
I am using ReactJS with Axios to call a protected API. I can receive authentication JWT access and refresh tokens successfully, user logins, but when the client tries to send the data request along with the access token, the server returns 401 unauthorized.
I have been stuck with this problem for a week, and tried everything
I set default headers as
axios.defaults.headers.common[‘Authorization’] = getJWT()
I set authServices.Js component as
import http from “…/common/httpService”;
import jwt_decode from ‘jwt-decode’;
export async function Login(username, password) {
const { data: JWT } = await http.post(“http://127.0.0.1:8000/auth/jwt/create”,
{ username, password });
localStorage.setItem("access ", JWT.access);
localStorage.setItem("refresh ", JWT.refresh);
}
export function logout() {
localStorage.removeItem("refresh ")
localStorage.removeItem("access ")
}
export function getCurrentUser() {
try {
const JWT = localStorage.getItem("access ")
return jwt_decode(JWT)
} catch (error) {
return null
}
}
export function getJWT() {
return localStorage.getItem("access ")
}
Login.js submit function as
doSubmit = async () => {
try {
const { data } = this.state;
await Login(data.username, data.password);
window.location = '/passenger'
} catch (error) {
if (error.response && error.response.status === 401) {
const errors = { ...this.state.errors }
errors.password = error.response.data.detail
this.setState({errors: errors})
}
}
};
I am looking for help on how to successfully send data with access token back to the Django server, and get access to the protected API
Thanks alot