spotty-amberS
Refine4y ago
5 replies
spotty-amber

cors issue when using axios interceptors.

I am using axios for my api request and whenever I try to send the login request to API without using axios interceptors it work fine but when I add the interceptors it will have an cors error.

Here is my code with axios interceptor:
const authAxios = axios.create();
authAxios.interceptors.request.use(
  // Here we can perform any function we'd like on the request
  (request: AxiosRequestConfig) => {
      if (request.headers) {
          // Set the Authorization header if it exists
          request.headers[
              "x-api-key"
          ] = API_KEY;
      } else {
          // Create the headers property if it does not exist
          request.headers = {
              "x-api-key": API_KEY,
          };
      }

      return request;
  },
);


And I am trying to use this axios instance in login as below
const response = await authAxios.post(`${API_BASE_URL}/login`, {phone_no, password});


Whenever I remove the interceptors code block it works without any issue but whenever I add it back it doesn't work. I have also tried to user login request as below:
const response = await authAxios.post(
  `${API_BASE_URL}/login`,
  {phone_no, password},
  {
    headers: {
      'x-api-key': <API_KEY>
    }
  }
);

But results in the same issue.
cors-issue.png
Was this page helpful?