如何在axios中设置头部和选项?

445

我使用Axios来执行HTTP post请求,代码示例如下:

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

这样正确吗?还是我应该做:

axios.post(url, params: params, headers: headers)

1
https://axios-http.com/docs/req_config - Archmede
16个回答

585

有几种方法可以做到这一点:

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

321

你可以通过带有头部信息的GET请求(例如使用JWT进行身份验证)来发送请求:

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

您也可以发送POST请求。

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

我的做法是这样设置请求:

 axios({
  method: 'post', //you can set what request you want to be
  url: 'https://example.com/request',
  data: {id: varID},
  headers: {
    Authorization: 'Bearer ' + varToken
  }
})

4
你的第二篇帖子请求中没有提供具体的标题头,请编辑完整的示例吗? - Striped
通过在interceptors.request中使用“data”=>它将覆盖我们正在使用的特定调用的实际body部分。因此,在这种情况下不要使用。 - Anupam Maurya
你必须遵循这种“Authorization: 'Bearer' + token”的标准,还是可以像Auth:token这样做?例如?我没有使用auth0 api,而是在node中自己进行操作,对于jwt和安全性方面的问题还不熟悉,如果问题比较愚蠢请见谅。 - Wiliam Cardoso

104

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


我曾经困惑于header是单数还是复数形式声明的。从你的回答中,这对我很有帮助。 - 钟智强

40
您可以像这样将配置对象传递给axios:
axios({
  method: 'post',
  url: '....',
  params: {'HTTP_CONTENT_LANGUAGE': self.language},
  headers: {'header1': value}
})

27

Here is the Right way:-

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


24

这是一个包含头部和响应类型的配置的简单示例:

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 可以是 'application/x-www-form-urlencoded' 或者 'application/json', 也可以使用 'application/json;charset=utf-8'。

responseType 可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'。

在这个例子中,this.data 是你想要发送的数据。它可以是一个值或一个数组。 (如果你想要发送一个对象,你可能需要将它序列化)


你能解释一下使用或不使用config关键字来设置headers的区别吗? - program_bumble_bee
1
使用配置变量可以生成更好、更易读的代码;没有其他的。@bubble-cord - gtamborero

19

您可以初始化默认标题 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)
        })

17

您还可以将所选标题设置为每个axios请求:

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

第二种方法

axios.defaults.headers.common['Authorization'] = 'AUTH_TOKEN';

16
如果您想要使用参数和头信息进行GET请求。
var params = {
  paramName1: paramValue1,
  paramName2: paramValue2
}

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

 Axios.get(url, {params, headers} ).then(res =>{
  console.log(res.data.representation);
});


9

尝试这段代码。

在示例代码中使用axios获取REST API。

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

希望就是帮助。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接