How to set header and options in axios?
Asked Answered
I

16

450

I use Axios to perform an HTTP post like this:

import axios from 'axios'
params = {'HTTP_CONTENT_LANGUAGE': self.language}
headers = {'header1': value}
axios.post(url, params, headers)

Is this correct? Or should I do:

axios.post(url, params: params, headers: headers)
Ivette answered 8/8, 2017 at 22:16 Comment(1)
axios-http.com/docs/req_configGadgetry
I
592

There are several ways to do this:

  • For a single request:

    let config = {
      headers: {
        header1: value,
      }
    }
    
    let data = {
      'HTTP_CONTENT_LANGUAGE': self.language
    }
    
    axios.post(URL, data, config).then(...)
    
  • For setting default global config:

    axios.defaults.headers.post['header1'] = 'value' // for POST requests
    axios.defaults.headers.common['header1'] = 'value' // for all requests
    
  • For setting as default on axios instance:

    let instance = axios.create({
      headers: {
        post: {        // can be common or any other method
          header1: 'value1'
        }
      }
    })
    
    //- or after instance has been created
    instance.defaults.headers.post['header1'] = 'value'
    
    //- or before a request is made
    // using Interceptors
    instance.interceptors.request.use(config => {
      config.headers.post['header1'] = 'value';
      return config;
    });
    
Interlaminate answered 9/8, 2017 at 4:49 Comment(0)
V
321

You can send a get request with Headers (for authentication with jwt for example):

axios.get('https://example.com/getSomething', {
 headers: {
   Authorization: 'Bearer ' + token //the token is a variable which holds the token
 }
})

Also you can send a post request.

axios.post('https://example.com/postSomething', {
 email: varEmail, //varEmail is a variable which holds the email
 password: varPassword
},
{
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})

My way of doing it,is to set a request like this:

 axios({
  method: 'post', //you can set what request you want to be
  url: 'https://example.com/request',
  data: {id: varID},
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})
Vidrine answered 12/2, 2018 at 19:52 Comment(3)
You second post request does not provide specific headers, can you edit it for full example ?Aga
by using data in interceptors.request => it will override your actuall body part from the specific call which where we are using. So not used in such case.Wed
Do you have to follow this standard of 'Authorization: 'Bearer ' + token' or can you do something like Auth: token for example? I'm not using auth0 api but doing my own in node, sorry if stupid question new to jwt and security stuff in generalGyration
F
104

axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)
Frangos answered 6/7, 2020 at 7:48 Comment(1)
I was confusing whether header is declared in singular or plural. From your answer, this helped me.Tenancy
E
40

You can pass a config object to axios like:

axios({
  method: 'post',
  url: '....',
  params: {'HTTP_CONTENT_LANGUAGE': self.language},
  headers: {'header1': value}
})
Empirin answered 9/8, 2017 at 2:20 Comment(0)
B
27

Here is the Right way:-

axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)
Bunder answered 22/11, 2019 at 7:26 Comment(0)
R
24

This is a simple example of a configuration with headers and responseType:

var config = {
  headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
  responseType: 'blob'
};

axios.post('http://YOUR_URL', this.data, config)
  .then((response) => {
  console.log(response.data);
});

Content-Type can be 'application/x-www-form-urlencoded' or 'application/json' and it may work also 'application/json;charset=utf-8'

responseType can be 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'

In this example, this.data is the data you want to send. It can be a value or an Array. (If you want to send an object you'll probably have to serialize it)

Restitution answered 7/3, 2018 at 21:31 Comment(2)
Can you explain the difference between setting the headers with our without the config keyword?Merovingian
Using a config variable generates a nicer and more readable code; nothing else @bubble-cordRestitution
N
19

You can initialize a default header axios.defaults.headers

 axios.defaults.headers = {
        'Content-Type': 'application/json',
        Authorization: 'myspecialpassword'
    }

   axios.post('https://myapi.com', { data: "hello world" })
        .then(response => {
            console.log('Response', response.data)
        })
        .catch(e => {
            console.log('Error: ', e.response.data)
        })
Neckcloth answered 21/8, 2018 at 13:44 Comment(0)
J
17

You can also set selected headers to every axios request:

// Add a request interceptor
axios.interceptors.request.use(function (config) {
    config.headers.Authorization = 'AUTH_TOKEN';
    return config;
});

Second method

axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';
Joinville answered 21/2, 2021 at 19:27 Comment(0)
A
16

if you want to do a get request with params and headers.

var params = {
  paramName1: paramValue1,
  paramName2: paramValue2
}

var headers = {
  headerName1: headerValue1,
  headerName2: headerValue2
}

 Axios.get(url, {params, headers} ).then(res =>{
  console.log(res.data.representation);
});
Aegaeon answered 14/5, 2019 at 11:19 Comment(0)
C
9

try this code

in example code use axios get rest API.

in mounted

  mounted(){
    var config = {
    headers: { 
      'x-rapidapi-host': 'covid-19-coronavirus-statistics.p.rapidapi.com',
      'x-rapidapi-key': '5156f83861mshd5c5731412d4c5fp18132ejsn8ae65e661a54' 
      }
   };
   axios.get('https://covid-19-coronavirus-statistics.p.rapidapi.com/v1/stats? 
    country=Thailand',  config)
    .then((response) => {
    console.log(response.data);
  });
}

Hope is help.

Catfall answered 29/3, 2020 at 7:57 Comment(0)
P
8

I have face this issue in post request. I have changed like this in axios header. It works fine.

axios.post('http://localhost/M-Experience/resources/GETrends.php',
      {
        firstName: this.name
      },
      {
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
      });
Psychophysics answered 7/4, 2020 at 17:19 Comment(0)
N
6

I had to create a fd=new FormData() object and use the [.append()][1] method before sending it through axios to my Django API, otherwise I receive a 400 error. In my backend the profile image is related through a OneToOne relationship to the user model. Therefore it is serialized as a nested object and expects this for the put request to work.

All changes to the state within the frontend are done with the this.setState method. I believe important part is the handleSubmit method at the end.

First my axios put request:

export const PutUser=(data)=>(dispatch,getState)=>{                                                                                                                                                                                                                                                                                                                                                                                                                                           
    dispatch({type: AUTH_USER_LOADING});                                                                                                                                                                                                 
    const token=getState().auth.token;                                                                                                                                                                                                                       
    axios(                                                                                                                                                                                                                                                   
    {                                                                                                                                                                                                                                                        
    ¦ method:'put',                                                                                                                                                                                                                                          
    ¦ url:`https://<xyz>/api/account/user/`,                                                                                                                                                                                           
    ¦ data:data,                                                                                                                                                                                                                                             
    ¦ headers:{                                                                                                                                                                                                                                              
    ¦ ¦ Authorization: 'Token '+token||null,                                                                                                                                                                                                                 
    ¦ ¦ 'Content-Type': 'multipart/form-data',                                                                                                                                                                                                               
    ¦ }                                                                                                                                                                                                                                                      
    })                                                                                                                                                                                                                                                       
    ¦ .then(response=>{                                                                                                                                                                                                                                      
    ¦ ¦ dispatch({                                                                                                                                                                                                                                           
    ¦ ¦ ¦ type: AUTH_USER_PUT,                                                                                                                                                                                                                               
    ¦ ¦ ¦ payload: response.data,                                                                                                                                                                                                                            
    ¦ ¦ });                                                                                                                                                                                                                                                  
    ¦ })                                                                                                                                                                                                                                                     
    ¦ .catch(err=>{                                                                                                                                                                                                                                          
    ¦ ¦ dispatch({                                                                                                                                                                                                                                           
    ¦ ¦ ¦ type:AUTH_USER_PUT_ERROR,                                                                                                                                                                                                                          
    ¦ ¦ ¦ payload: err,                                                                                                                                                                                                                                      
    ¦ ¦ });                                                                                                                                                                                                                                                  
    ¦ })                                                                                                                                                                                                                                                     
  }      

My handleSubmit method needs to create the following json object, where the image attribute gets replaced by the actual user input:

user:{
username:'charly',
first_name:'charly',
last_name:'brown',
profile:{
image: 'imgurl',
  }
}

Here is my handleSumit method inside the component: check append

handleSubmit=(e)=>{                                                                                                                                                                                                                                      
¦ e.preventDefault();                                                                                                                                                                                                                                                                                                                                                                                                                  
¦ let fd=new FormData();                                                                                                                                                                                                                                 
¦ fd.append('username',this.state.username);                                                                                                                                                                                                             
¦ fd.append('first_name',this.state.first_name);                                                                                                                                                                                                         
¦ fd.append('last_name',this.state.last_name);                                                                                                                                                                                                                                                                                                                                                                                                                  
¦ if(this.state.image!=null){fd.append('profile.image',this.state.image, this.state.image.name)};                                                                                                                                                                                                                                                                                                                                                        
¦ this.props.PutUser(fd);                                                                                                                                                                                                                                
}; 
Neper answered 30/12, 2020 at 1:47 Comment(0)
F
5

Using Async/Await

Axios post signature

post(url: string, data?: any, config?: AxiosRequestConfig): Promise<AxiosResponse> Both data and config are Optional

AxiosRequestConfig can be looked at - https://github.com/axios/axios/blob/e462973a4b23e9541efe3e64ca120ae9111a6ad8/index.d.ts#L60

 ....
 ....
 try {
   ....
   ....
   const url = "your post url"
   const data = {
     HTTP_CONTENT_LANGUAGE: self.language
   }
   const config = {
      headers: {
       "header1": value
      },
      timeout: 1000,
      // plenty more options can be added, refer source link above
    }

   const response = await axios.post(url, data, config);
   // If Everything's OK, make use of the response data
   const responseData = response.data;
   ....
   ....
 }catch(err){
   // handle the error
   if(axios.isAxiosError(err){
     ....
     ....
   }
 }
Fleshy answered 10/10, 2021 at 9:33 Comment(0)
C
3
var axios = require("axios").default;

var options = {
  method: 'GET',
  url: 'https://api.pexels.com/v1/curated',
  params: {page: '2', per_page: '40'},
  headers: {Authorization: '_authkey_'}
};

axios.request(options).then(function (response) {
  console.log(response.data);
}).catch(function (error) {
  console.error(error);
});
Choir answered 6/10, 2022 at 8:31 Comment(1)
As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.Ingunna
O
2

You can use params and body together in a request with axios.

  sendAllData (data) {
        axios
        .post(API_URL + "receiveData", JSON.stringify(data), {
          headers: { "Content-Type": "application/json; charset=UTF-8" },
          params: { mail: [email protected] }, //Add mail as a param
        })
        .then((response) => console.log("repsonse", response.status)); 
  }
Otha answered 14/12, 2022 at 6:22 Comment(0)
B
-9

@user2950593 Your axios request is correct. You need to allow your custom headers on server side. If you have your api in php then this code will work for you.

header("Access-Control-Allow-Origin: *");   
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, HEAD");
header("Access-Control-Allow-Headers: Content-Type, header1");

Once you will allow your custom headers on server side, your axios requests will start working fine.

Beseech answered 16/10, 2020 at 8:54 Comment(1)
The OP was asking for nodejs, not php though , just sayingTenancy

© 2022 - 2024 — McMap. All rights reserved.