Home > Net >  Problem with dynamic request header in axios template
Problem with dynamic request header in axios template

Time:12-01

In my react app, I created an api.js file which creates an api object with axios.create and exports it as default. So, I use that template to make the API requests. The problem is that, one of the headers in created axios api object must be dynamic. For example, see the locale header below:

At first it may be something like this:

export default api = axios.create({
    baseURL: process.env.REACT_APP_API_URL,
    headers: {
      post: {
        "Content-Type": "application/json;charset=utf-8",
        "Access-Control-Allow-Origin": "*",
        locale: "en",
      },
      get: {
        locale: "en",
      },
    },
  });

But after some time it can be updated to some other locale, like "en" should be changed with "fr" for example. How can I update it, and make sure when it gets updated it changes in every place api is imported.

I can't use ContextApi etc, because I need to use that api in index.js file too, which, because of not being a react component, doesn't support use of hooks.

CodePudding user response:

Sounds like a job for Axios interceptors...

import axios from "axios"

// some kind of storage for your locale
let locale = "en"

// some way of changing it
export const setLocale = (newLocale) => {
  locale = newLocale
}

const api = axios.create({
  baseURL: process.env.REACT_APP_API_URL,
})

// register a synchronous request interceptor
api.interceptors.request.use(config => ({
  ...config,
  headers: {
    ...config.headers,
    locale // merge the "locale" into the request config headers
  }
}), null, { synchronous: true })

export default api

Also, Access-Control-Allow-Origin is a response header that comes from the server. It does not belong in your request and in general will more than likely cause CORS errors.

Also, the default content-type when posting JS objects in Axios is application/json so you typically don't need to set it.

  • Related