如何在需要标头的axios post请求中使用config参数

问题描述 投票:2回答:2

我试图在我的反应代码中使用axios发送一个post请求,同时需要'headers parameter'和'config parameter'。我发现在axios中编写post请求有两种类型:

  1. axios.post(url,data,config)
  2. axios({url:url,方法:'post',headers:headers,data:data})

在类型1中我们不能发送头参数,在类型2中我们不能发送配置参数。

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

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

javascript reactjs xmlhttprequest httprequest axios
2个回答
2
投票

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

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

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

3
投票

基于doc

你可以在config中设置标题!

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 
})
© www.soinside.com 2019 - 2024. All rights reserved.