error.response is undefined
I'd like to know if it's a problem with my code or server. If the error status is 401, I'll get a new token through refresh token. if its 500 or something, I'll route the others to the error page.
export const authClient = axios.create({
baseURL: BASE_URL,
headers: {
"Content-Type": "application/json",
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,PATCH,OPTIONS",
"Access-Control-Allow-Credentials": "include",
withCredentials: true,
},
});
authClient.interceptors.request.use(
(config) => {
const accessToken = getAccessToken();
if (accessToken && config.headers) {
config.headers.Authorization = `Bearer ${accessToken}`;
}
return config;
},
(error) => {
return Promise.reject(error);
}
);
authClient.interceptors.response.use(
async (response) => {
return response;
},
async (error) => {
const originalRequest = error.config;
try {
const newAccessToken = await getNewTokens().catch((tokenError) => {
throw tokenError;
});
if (newAccessToken) {
originalRequest.headers.Authorization = `Bearer ${newAccessToken}`;
return authClient(originalRequest);
}
} catch (refreshError) {
return Promise.reject(refreshError);
}
window.location.href = "/error";
return Promise.reject(error);
}
);
I want to use it after receiving an error response.
I only get AxiosError : NetworkError
There's a few scenarios where a request can fail with no response data:
In those cases, error.response will be undefined. You can try looking into error.cause to investigate further.
You didn't specify in your question, but assuming it's frontend code, it's likely you are running into CORS issues. Check in your devtools console if you aren't getting any errors like the following:
Access to fetch at 'https://yourserver.com/' from origin 'https://yourwebsite.com' has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.