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

195
Vistas
How can I use Axios interceptors to add some headers to responses?

In my Reactjs app , I want to add an interceptor which can append some headers to some backend responses

So, I tried this :

    export default function App() {
      axios.interceptors.response.use(
        (config)=> {
          config.headers['myheader'] = 'myvalue'; // <-- THIS IS MY CUSTOM HEADERS
          return config;
        },
        (error) => {
          // ON ERREOR
        })
       ......
      );

And I suppose like that that my header would be append in every back-end response. But that doesn't seem to work.

Suggestions ??

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

0

Add a request interceptor

axios.interceptors.request.use(
    config => {
        const token = localStorage.getItem('auth_token');
        if (token) {
            config.headers['Authorization'] = 'Bearer ' + token;
        }
        config.headers['Content-Type'] = 'application/json';
        return config;
    },
    error => {
        Promise.reject(error)
});

Add a response interceptor

axios.interceptors.response.use((response) => { // block to handle success case
    return response
 }, function (error) { // block to handle error case
    const originalRequest = error.config;
 
    if (error.response.status === 401 && originalRequest.url ===
 'http://dummydomain.com/auth/token') { // Added this condition to avoid infinite loop 

 
        // Redirect to any unauthorised route to avoid infinite loop...
        return Promise.reject(error);
    }
 
    if (error.response.status === 401 && !originalRequest._retry) { // Code inside this block will refresh the auth token
 
        originalRequest._retry = true;
        const refreshToken = 'xxxxxxxxxx'; // Write the  logic  or call here the function which is having the login to refresh the token.
        return axios.post('/auth/token',
            {
                "refresh_token": refreshToken
            })
            .then(res => {
                if (res.status === 201) {
                    localStorage.setItem('auth_token',res.data);
                    axios.defaults.headers.common['Authorization'] = 'Bearer ' + localStorage.getItem('auth_token');
                    return axios(originalRequest);
                }
            })
    }
    return Promise.reject(error);
});

Click here to see the topic in detail.

about 4 years ago · Juan Pablo Isaza Denunciar

0

Try this:

    axios.interceptors.response.use(
      function (response) {
        const edited_response = response;
        edited_response.headers["custom_header"] = "test";
        return edited_response;
      },
      function (error) {
        // Any status codes that falls outside the range of 2xx cause this function to trigger
        // Do something with response error
        return Promise.reject(error);
      }
    );
about 4 years ago · Juan Pablo Isaza Denunciar

0

Hey the reason thats not working because you are calling use method to update the repsonse headers but to be able to send headers to your backend apis you need to call the use method from request object. Here's how you can do :

axios.interceptors.request.use(
  function handleRequestInterceptor(config) {
    const modifiedConfig = {
      ...config,
      headers: {
        myheader: "myvalue",  <=== your custom headers like auth etc.
        ...config.headers,
      },
    };
    return modifiedConfig;
  },
  function handleRequestInterceptorError(error) {
    return Promise.reject(error);
  }
);
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