How to set header and options in axios?

JavascriptPostAxios

Javascript Problem Overview


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)

Javascript Solutions


Solution 1 - Javascript

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;
     });
    

Solution 2 - Javascript

> 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
  }
})

Solution 3 - Javascript

axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)

Solution 4 - Javascript

You can pass a config object to axios like:

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

Solution 5 - Javascript

Here is the Right way:-

axios.post('url', {"body":data}, {
    headers: {
    'Content-Type': 'application/json'
    }
  }
)

Solution 6 - Javascript

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)

Solution 7 - Javascript

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)
        })

Solution 8 - Javascript

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';

Solution 9 - Javascript

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);
});

Solution 10 - Javascript

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.

Solution 11 - Javascript

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' }
      });

Solution 12 - Javascript

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);                                                                                                                                                                                                                                
}; 

Solution 13 - Javascript

Using Async/Await

> Axios post signature > > post(url: string, data?: any, config?: AxiosRequestConfig): Promise> > 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){
     ....
     ....
   }
 }

Solution 14 - Javascript

@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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser2950593View Question on Stackoverflow
Solution 1 - Javascriptriyaz-aliView Answer on Stackoverflow
Solution 2 - JavascriptRolandView Answer on Stackoverflow
Solution 3 - JavascriptSethy ProemView Answer on Stackoverflow
Solution 4 - Javascriptsjc42002View Answer on Stackoverflow
Solution 5 - JavascriptPrateek AroraView Answer on Stackoverflow
Solution 6 - JavascriptgtamboreroView Answer on Stackoverflow
Solution 7 - JavascriptMorris SView Answer on Stackoverflow
Solution 8 - JavascriptJsowaView Answer on Stackoverflow
Solution 9 - JavascriptRishith PolojuView Answer on Stackoverflow
Solution 10 - JavascriptsuperupView Answer on Stackoverflow
Solution 11 - JavascriptNajathiView Answer on Stackoverflow
Solution 12 - JavascriptErnst PlesiutschnigView Answer on Stackoverflow
Solution 13 - JavascriptBikashView Answer on Stackoverflow
Solution 14 - JavascriptAdnan AhmadView Answer on Stackoverflow