4👍
As per the screenshot of the postman request and the code snippets shared, there seems to be a mismatch in the value of Authorization.
In postman its: Bearer: your_auth_token
In axios headers its: Bearer your_auth_token
The colon after Bearer
might just be the issue here.
Also, don’t set the authorization header directly in axios.create
. Instead create an axios instance and use axios interceptors on the request obj and set the auth token there. Because your auth token can expire, and when you refresh your token, axios will not update the new token from local storage. axios.create
only runs once when the instance is created. So, it will use the token that was initially added. But, Axios Interceptors on the other hand are called each time a request is made, therefore it will fetch the token from local storage before each request. This ensures you are sending valid tokens instead of stale ones. Hope it helps.
import axios from 'axios'
import { BASE_URL } from './constants'
const instance = axios.create({
baseURL: BASE_URL,
})
instance.interceptors.request.use(
(config) => {
const token = localStorage.getItem('Authorization')
if (token) {
config.headers.Authorization = `Bearer ${token}`
config.headers["Content-Type"] = "application/json"
} else {
// Do something... Usually logout user.
}
return config
}
)
export default instance
http-common.js should look something like above.