【问题标题】:How to have config parameter in axios post request with headers required如何在需要标头的axios发布请求中具有配置参数
【发布时间】:2019-02-16 08:34:51
【问题描述】:

我试图在我的反应代码中使用 axios 发送一个帖子请求,这两个都需要 “标头参数”和“配置参数”同时进行。我发现在axios中写post请求有两种类型:

  1. axios.post(url, data, config)

  2. axios({ 网址:网址, 方法:'发布', 标题:标题, 数据:数据 })

在类型 1 中我们无法发送 headers 参数,在类型 2 中我们无法发送配置参数。

那么有什么办法可以解决这个问题吗?

我使用 xml httpRequest 而不是 axios 解决了它,但我很好奇我们可以使用 axios 解决它的方式。

【问题讨论】:

    标签: javascript reactjs xmlhttprequest httprequest axios


    【解决方案1】:

    您的假设是错误的,您可以在请求配置中设置标头

    https://github.com/axios/axios#request-config

    {
       headers: {'X-Requested-With': 'XMLHttpRequest'},
       ...
    }
    

    【讨论】:

      【解决方案2】:

      基于doc

      你可以在config中设置header!

      axios.post(url, data, {headers : {'X-Requested-With': 'XMLHttpRequest'} })
      

      或者您可以将所有选项作为对象发送

      axios.request ({
          url: '/user',
          method: 'post',
          data: {
              firstName: 'Fred'
          },
          headers: {'X-Requested-With': 'XMLHttpRequest'},
      
          // ... and other options 
      })
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-04-30
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-02
        • 1970-01-01
        • 2019-03-07
        相关资源
        最近更新 更多