I'm getting an incredibly annoying and difficult to debug problem using Axios (React) with a rest api (DRF).
When I first attempt to make a request (mostly POST) the function fails and printing Err returns:
Error: Network Error at createError (createError.js:16) at XMLHttpRequest.handleError (xhr.js:117)
I can see it's pointing at the createError which doesn't provide great deal of feedback; it could be network issues (not likely) or CORS; my axios instance is this. Could I be missing something critical in my header?
export const axiosInstance = axios.create({
baseURL: baseUrl,
timeout: 1000,
headers: {
Authorization: localStorage.getItem('access_token')
? 'JWT' + localStorage.getItem('access_token')
: null,
'Content-Type': 'application/json',
accept: 'application/json',
},
});
I understand the problem maybe Network related or CORS related but the strange thing (to me anyway) is that it allows the connection on trying the second or third time. Exactly the same (just clicking the button) and once the endpoint has been successfully reached it will continue to do it first time after a little while; as if it needs 'waking up'.
If it were a CORS' issue it would just block the attempt every time, surely? Irrespective of that I do have Cors middleware in DRF settings and it is the first item in the list as well as in the installed apps. The url is in the CORS_ALLOWED_ORIGINS also. So my settings seem fine; I've also used this configuration numerous times before so I know it works, also the request passes after repeated attempts.
I'm also hosting on Azure which has a built in CORS protection feature; I've allowed all hosts there as well by using the * (yes, I will add the urls but once I've got to the bottom of this).
I can probably get around it by using some sort of retry method in Axios but I want/need to know why it fails the first time as it doesn't seem ideal to have to retry an endpoint.
Here is my usage/implementation of axios.create
axiosInstance
.post('/accounts/login/', {
email: formData.email,
password: formData.password,})
.then((res) => {
localStorage.setItem('access token', res.data.access);
localStorage.setItem('refresh token', res.data.refresh);
history.push('/targetnda');})
.catch(err => {
console.log('here', err)
const resp = err.response.data
// data undefined because obviously there is no response. Error returns Network error})
with..
export const axiosInstance = axios.create({
baseURL: baseUrl,
timeout: 1000,
headers: {
Authorization: localStorage.getItem('access_token')
? 'JWT' + localStorage.getItem('access_token')
: null,
'Content-Type': 'application/json',
accept: 'application/json',
},
});
Thank you for your patience and reading; please be kind to my React code (newbie) =/
timeoutfromaxios.create.