Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

164
Vistas
Problem with dynamic request header in axios template

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.

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda