How to set header and options in axios?

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

14 Answers

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

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

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

Also you can send a post request.

axios.post(' { 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: ' data: {id: varID}, headers: { Authorization: 'Bearer ' + varToken } }) 
3
axios.post('url', {"body":data}, { headers: { 'Content-Type': 'application/json' } } )
1

You can pass a config object to axios like:

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

Here is the Right way:-

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

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(' 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)

2

You can initialize a default header axios.defaults.headers

 axios.defaults.headers = { 'Content-Type': 'application/json', Authorization: 'myspecialpassword' } axios.post(' { data: "hello world" }) .then(response => { console.log('Response', response.data) }) .catch(e => { console.log('Error: ', e.response.data) }) 

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

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

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(' country=Thailand', config) .then((response) => { console.log(response.data); }); } 

Hope is help.

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

axios.post(' { firstName: this.name }, { headers: { 'Content-Type': 'application/x-www-form-urlencoded' } }); 

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:` ¦ 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); }; 

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 -

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

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

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

You Might Also Like