I’m experiencing a 401 (Unauthorized) error when trying to fetch user data with a token in my React application using Axios. This happens when I attempt to call the getUserByToken function. getUserByToken
The authToken is set correctly in the Redux store, and I’m logging it right before the request. Here’s how I set the token:
dispatch(auth.actions.login(token));
I’m using Axios interceptors to attach the token to the headers:
export default function setupAxios(axios, store) {
axios.interceptors.request.use(
config => {
const {
auth: { authToken }
} = store.getState();
// Log the token before adding it to the headers
console.log("Token in interceptor:", authToken);
if (authToken) {
config.headers.Authorization = `Bearer ${authToken}`;
}
return config;
},
err => Promise.reject(err)
);
}
ps: the token is not present in the request headers in my browser’s developer tools (under the “Network” tab)
What could be causing the 401 (Unauthorized) error despite having the token set?
Are there any common issues with token handling in Axios that I should be aware of?
I expect to receive user data when the token is valid.
Additional Information
I’m using React, Redux, and Redux-Saga.
The API endpoint works fine with valid tokens when tested with tools like Postman
this is my
authredux.js
authcrud.js
profile.js
app.js
Asma123 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.