Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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) 
like image 878
user2950593 Avatar asked Aug 08 '17 22:08

user2950593


People also ask

How do you pass headers and params in Axios?

When you are using the Axios library and to pass custom headers, you need to construct headers as an object with the key name 'headers'. The 'headers' key should contain an object, here it is Content-Type and Authorization .

How do I use Axios with headers?

To send an Axios POST request with headers, you need to use the headers option. With axios. post() , the first parameter is the URL, the 2nd parameter is the request body, and the 3rd parameter is the options . For example, below is how you set the Content-Type header on an HTTP POST request.


2 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; }); 
like image 189
riyaz-ali Avatar answered Nov 08 '22 15:11

riyaz-ali


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   } }) 
like image 26
Roland Avatar answered Nov 08 '22 14:11

Roland