Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

163
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!