Encountering a problem with retrieving error responses when implementing an axios interceptor

error.response is undefined
I'm trying to figure out if the issue lies within my code or the server. If the error status is 401, I will fetch a new token using the refresh token. For error statuses like 500, I will direct users 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 intend to implement this functionality after encountering an error response.
Currently, I am only receiving AxiosError : NetworkError

Answer №1

There are several situations where a request may fail without receiving any response data:

  • unstable network connection
  • timeout limit reached
  • domain resolution failure
  • HTTPS misconfiguration
  • CORS misconfiguration

In such cases, the error.response will not be defined. You can explore the error.cause for further investigation.

Although you did not specify in your query, if it is related to frontend code, it is probable that you are encountering CORS-related issues. Check your devtools console for any errors similar to 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.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error: The field 'password' is not found in the specified type

Hey, I'm fairly new to TypeScript and encountering an error with my express and MongoDB application. Let's take a look at my User.ts model. import mongoose from "mongoose"; interface IUser { username: string; password: string ...

The issue arises when using styled components in both server and client environments, causing a mismatch when importing from a common

I am encountering an issue with using a styled component called Button exported from packages/common in my simple React app, which I want to use in my NextJs application located in packages/landing-page. While trying to import the styled-components as sho ...

What is the recommended way to handle data upon retrieval from a Trino database?

My goal is to retrieve data from a Trino database. Upon sending my initial query to the database, I receive a NextURI. Subsequently, in a while loop, I check the NextURI to obtain portions of the data until the Trino connection completes sending the entire ...

Is it beneficial to utilize both revalidatePath and Return Value in a Server Action?

Looking for some assistance Description: I am utilizing useFormState with a server action. However, when I include both revalidatePath and a return value, the revalidatePath functions correctly but does not return any value state for useFormState. When I r ...

What does the typeof keyword return when used with a variable in Typescript?

In TypeScript, a class can be defined as shown below: class Sup { static member: any; static log() { console.log('sup'); } } If you write the following code: let x = Sup; Why does the type of x show up as typeof Sup (hig ...

Using Angular2, you can dynamically assign values to data-* attributes

In my project, I am looking to create a component that can display different icons based on input. The format required by the icon framework is as follows: <span class="icon icon-generic" data-icon="B"></span> The data-icon="B" attribute sp ...

What benefits does storing images in the Next.js public folder offer?

It's interesting how I can place my images practically anywhere and they still work perfectly. But, according to Next.JS, it's actually recommended to store the images in the public folder. What could be the benefits of doing this? ...

What is the process for moving information between files?

I have two files which are named as, employee-rates-controller.ts: private load() { return this.entityService .load(this.$scope.projectRevisionUid) .then(resp => { localStorage.removeItem('employeerates'); this.$ ...

Angular input field displaying X

Hey everyone, I'm currently working with Angular and typescript. I have a requirement to hide the first 8 characters that the user enters and only show the remaining 4 characters. Update: I have included a link to the Stackblitz demo Stackblitz <i ...

utilizing adaptive image sizing in next.js with tailwindcss

Lately, I've noticed a lot of changes in the way next.js handles image sizing across different versions. Currently, I'm on version "next": "13.4.4", and I'm looking to create responsive images that take up 20% of the scre ...

Is there a way to customize the language used for the months and days on the DatePicker

Is there a way to change the language of the DatePicker (months and days) in Material UI? I have attempted to implement localization through both the theme and LocalizationProvider, but neither method seems to work. Here are some resources I have looked a ...

Display or conceal password text with Nativescript

I am working on a login form where I need to toggle the visibility of the password text. Below is the code snippet that I have implemented. Here is the code I tried: <GridLayout margin="10" verticalAlignment="center" backgroundColor="#ffffff"> ...

What is the process for fetching data from a remote GraphQL server and utilizing it as global variables in the application?

I am currently facing a challenge in finding a solution to this issue... My goal is to retrieve data from a remote CMS using GraphQL, and have it accessible on any page throughout the app without the need to fetch it individually for each page. I want to ...

`Running ng serve will result in the creation of a 'dist' folder within each app sub

Since beginning my project, I have encountered an issue that is both normal and frustrating. The dist folder is being created with incomplete information related to the components inside it. dashboard dist (unwanted) components panel dist (unwanted) c ...

What is the process for launching a TypeScript VS Code extension from a locally cloned Git repository?

Recently, I made a helpful change by modifying the JavaScript of a VSCode extension that was installed in .vscode/extensions. Following this, I decided to fork and clone the git repo with the intention of creating a pull request. To my surprise, I discove ...

Ensure that the interface limits the key value to match precisely the value of a constant in Typescript

Seeking assistance in understanding how to enforce a specific type for an optional key within an interface: const FIRST = "FIRST" const SECOND = "SECOND" interface TSomeInterface { element: Element order?: typeof FIRST | typeof ...

Integrate Shopify Polaris hyperlinks with Nextjs anchor tags

While working with Shopify Polaris, I noticed that many internal components generate a single static <a /> tag. This has caused an issue in my NextJS app as clicking on the link reloads the entire page. Is there a way to make Shopify Polaris links f ...

TypeScript's Awaitable concept

Lately, I have been utilizing async / await functions quite frequently in my JavaScript projects. As I make the transition to TypeScript, I am gradually converting some sections of my code bases. In certain scenarios, my functions require a function as an ...

What is the best way to define a function that accepts an object with a specific key, while also allowing for any additional keys to be passed

Typescript allows us to define an interface for an object that must have a key and can also allow additional keys: interface ObjectWithTrace { trace: string; [index: string]: any } const traced: ObjectWithTrace = { trace: 'x', foo: 'bar ...

Debugging a node.js application remotely using SAP Cloud Foundry

Having successfully deployed multiple node.js express services on SAP Cloud Foundry, we have encountered a roadblock in the form of remote debugging. Recognizing that others may be facing similar challenges, we are putting forth a direct inquiry: What is ...