Himanshu Menon
Himanshu Menon

Reputation: 41

Unable to get header when using axios.create

I created an axios instance in axios.js like following

const instance = axios.create({
  baseURL: "url",
  timeout: 5000,
  headers: {
    authorization:
      "key",
  },
});

export default instance;

and I am using this like following

const responce = await instance.get(url)

but the problem is that my api is unable to access headers and it shows me the error that authorization key is required. My api works fine if I manually pass the header like following

 const responce = await instance.get(url, {
        headers: {
          authorization:
            "key",
        },
      })

Upvotes: 1

Views: 380

Answers (1)

Elvin
Elvin

Reputation: 584

Try this one.

instance.defaults.headers.common['authorization'] = "key";

Alternative way

const instance = axios.create();

instance.interceptors.request.use(
  function (config) {
    config.baseURL = BASE_URL;
    config.headers =  {
      authorization:
        "key",
    }
    return config;
  },
  function (error) {
    Promise.reject(error);
  }
);

export default instance;

Upvotes: 1

Related Questions