I have a delay built into my axios module for testing react UI spinners etc.
The mock_delay works perfectly on my local machine but after I npm build and deploy it appears the promise does not return.
If I set mock_delay false this works on both my local and remote (built, nginx) machine. But if I set a time out then, on the built server I see the "console.log('config.mock_delay' etc" but not the "console.log('response', response)".
Any clues??
const Server = axios.create({
baseURL: AUTH_API2_URL,
timeout: 5000,
mock_delay: false, //800,
headers: {
'Authorization': currentJWTHeader(),
'Content-Type': 'application/json',
'accept': 'application/json'
}
})
Server.interceptors.request.use((config) => {
if (config.mock_delay) {
console.log('config.mock_delay', config.mock_delay)
return new Promise(resolve =>
setTimeout(() => resolve(config), config.mock_delay))
}
return config
})
Server.interceptors.response.use(
response => {
console.log('response', response)
return response
}
}
I don't know how your local version work but for production it has reason for not working.
1st, the axios interceptor use requires function with signature like this: req => req. It means receive a request and return an enhanced request.
Ref here:
https://axios-http.com/docs/interceptors
https://masteringjs.io/tutorials/axios/interceptors
So with your code, it is correct when mock_delay is false: config => config
But when mock_delay is not false, it is config => Promise, then your code is failed because of wrong expectation => that's why you never see the response.
Let twist it a bit:
function delay(ms) {
// my prev answer has a mistake
// that is the `resolve` function is undefined
// return new Promise((resolve) => setTimeout(resolve, ms));
// fix here
return new Promise(() => setTimeout(() => {}, ms));
}
// remember to add async keywork
Server.interceptors.request.use(async (config) => {
if (config.mock_delay) {
console.log('config.mock_delay', config.mock_delay)
// with await, this will wait for the time of mock_delay
await delay(config.mock_delay)
}
// finally still return config
return config
})