如何在 axios 中设置标题和选项? [英] How to set header and options in axios?

查看:32
本文介绍了如何在 axios 中设置标题和选项?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 Axios 执行这样的 HTTP 帖子:

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)

推荐答案

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

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
    

  • 用于在 axios 实例上设置为默认值:

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

  • 这篇关于如何在 axios 中设置标题和选项?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆