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

72
Views
Add additional headers in Axios create function

I have this already made function to send requests from Axios,

export const http = axios.create({
  baseURL: 'https://someurl/api',
  headers: {
    'Content-type': 'application/json',
    Accept: 'application/json',
  },
});

So I can call this method anywhere in my application,

   import {http} from 'src/helpers/HttpHelper';

   http
      .post(
        '/users',
        {name: 'mishen'},
      )
      .then(res => console.log(res))
      .catch(error => console.log());

Since there are protected routes too which require a bearer token I tried to do something like this inside my component,

import {useContext} from 'react';
import {http} from 'src/helpers/HttpHelper';

const MyComponent = () => {
  const {userToken} = useContext(AuthContext);
  const signUpUser = () => {
    http
  .post(
    '/app_user_role_selection',
    {name: 'mishen'},
    {headers: {Authorization: `Bearer ${userToken}`}}
  )
  .then(res => console.log(res))
  .catch(error => console.log());
 }
 ...
}

However, this is not working.

almost 4 years ago · Santiago Trujillo
1 answers
Answer question

0

You can use axios interceptors.

export const http = axios.create({
  baseURL: "url",
  headers: {
    "Content-type": "application/json",
    Accept: "application/json"
  }
});

http.interceptors.request.use(async (config) => {
  const value = await AsyncStorage.getItem("your key");
  if (value !== null) {
    config.headers["Authorization"] = `Bearer ${value}`;
  }

  return config;
});


const MyComponent = () => {
  const signUpUser = () => {
    http
      .post(
        "/app_user_role_selection",
        { name: "mishen" }
      )
      .then((res) => console.log(res))
      .catch((error) => console.log());
  };
};

almost 4 years ago · Santiago Trujillo 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!