I have a ReactJS project, where I'm using an axios interceptor to set a jwt token into each request that requires it. I'm also trying to use a response interceptor, which I've defined to be included in the same "custom" instance. However, the response interceptor doesn't trigger after any requests, as long as my request interceptor is active.
If I remove the request interceptor (by just commenting it out), my response interceptor starts working. It seems like my request interceptor is canceling out any further intercepting by axios.
My interceptor file exporting the custom axios instance including the intercept-logic:
import axios from 'axios'
import { utils } from './index'
let user = null
let token = null
const customAxios = axios.create({})
// Request interceptor
customAxios.interceptors.request.use(
(req) => handleRequest(req),
(e) => {
console.log('Error from request interceptor: ', e.response)
return handleError(e)
}
)
// Response interceptor
customAxios.interceptors.response.use(
(res) => handleResponse(res),
(e) => {
console.log('Error intercepted from response: ', e.response)
return handleError(e)
}
)
const handleRequest = (request) => {
addTokenIfExists(request)
// TODO: future custom request modifiers
return request
}
const handleResponse = (response) => {
console.log('Intercepted response:', res)
// TODO: future custom response modifiers
return response
}
const handleError = (e) => {
// TODO: when this works for response add to Redux error variable to display in app
if (e.response.status === 401) {
console.log('Code was 401: Authorization error from response')
}
return Promise.reject(e)
}
const addTokenIfExists = (req) => {
user = JSON.parse(window.localStorage.getItem('loggedUser'))
token = `Bearer ${user ? user.token : null}`
// Check if token is expired with every request, if it is, remove it from localStorage
token = utils.checkIfTokenExpired(user, token)
// Add token to each request if it's found
if (token) {
req.headers = {
...req.headers,
Authorization: token,
}
}
console.log('Intercepted request:', req)
return req
}
export default customAxios
My user-service file, as an example using the custom axios instance:
import axios from '../services/interceptors'
const baseUrl = '/users'
const getUser = async (id) => {
let res = null
await axios
.get(baseUrl + '/' + id)
.then((req) => {
res = req.data
})
.catch((e) => {
return Promise.reject(e)
})
return res
}
const userService = {
getUser,
}
export default userService
I'm planing to use the response interceptor to modify the errors and add custom error-objects for the front-end of my application, but for now I can't even get the response to print in my console from the handleResponse() function, unless i remove the request interceptor, as mentioned in the description of my problem.
Could someone help me understand why the response interceptor isn't getting triggered?
Edit: seems like there was a bug with past Axios version (0.21.2), updating to 0.25.0 resolved the issue.