4
votes

I was trying to send a post request using axios in my react code which needed both 'headers parameter' and 'config parameter' at the same time. I found out that there is two types for writing post requests in axios:

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

  2. axios({ url :url, method: 'post', headers: headers, data: data })

In type 1 we can't send headers parameter and in type 2 we can't send config parameter.

So is there any way to solve this problem?

I solved it using xml httpRequest instead of axios, but I'm curious about the way we could solve it using axios.

2

2 Answers

5
votes

your assumption is wrong you can set the headers in the request config

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

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

base on doc

you can set header in config !

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

or you can send all options as a object

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

    // ... and other options 
})