Home > front end >  CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers
CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers

Time:11-02

I'm making a GET type request to an api that requests two authentication headers, one of them is called token and the other Authentication.

I'm passing the two required parameters, as in the printscreen below:

enter image description here

In return, I get the error:

Access to XMLHttpRequest at 'https://pay.apiname.com.br/v1/sellers/d.....2/payments/list' from origin 'http://10.0.0.150:3006' has been blocked by CORS policy: Request header field token is not allowed by Access-Control-Allow-Headers in preflight response.

I'm using axios to make requests. In the file below you have the configuration of the request for this specific middleware. I run this request even in redux action when necessary.

paymentApi: {
    client: axios.create({
      baseURL: process.env.API,
      responseType: 'json',
    }),
    options: {
      returnRejectedPromiseOnError: true,
      interceptors: {
        request: [
          ({ getState }, config) => {
            // here I look for the user information from the state, where it contains the authorization and token needed for the header.
            const { auth } = getState().get('login').toJS();

            return {
              ...config,
              headers: {
                ...(config.headers || {}),
                token: auth.user.token_parcela
                  ? `${auth.user.token_parcela}`
                  : undefined,
                Authorization: auth.user.api_key_parcela
                  ? `${auth.user.api_key_parcela}`
                  : undefined,
                Accept: 'application/json',
                'Content-Type': 'application/json',
              },
            };
          },
        ],
        response: [
          {
            success: (store, response) => response,
            error: (_store, error) => {
              console.error(error);
              return Promise.reject(error);
            },
          },
        ],
      },
    },
  },
  

Strange thing is that if you try to make this request using postman, I can do it without any problems, see the printscreen below.

enter image description here

CodePudding user response:

The issue is not related to your code, the API where it is hosted/built upon needs to allow CORS origin, and you will have to specify your website from which you are calling this API as the origin.

Read more about CORS here - CORS

Also it works in Postman is because the API is called directly and not from any source/origin/website unlike your code.

  • Related