Setting Request Headers with Axios
Apr 27, 2019
To set HTTP request headers with
an axios GET request, you should pass
an object with a headers
property as the 2nd argument.
const axios = require('axios');
// httpbin.org gives you the headers in the response
// body `res.data`.
// See: https://httpbin.org/#/HTTP_Methods/get_get
const res = await axios.get('https://httpbin.org/get', {
headers: {
'Test-Header': 'test-value'
}
});
res.data.headers['Test-Header']; // "test-value"
With PUT and POST requests, the 2nd argument is the request body, so you should
pass an object with a headers
property as the 3rd argument.
const res = await axios.post('https://httpbin.org/post', { hello: 'world' }, {
headers: {
'Test-Header': 'test-value'
}
});
res.data.headers['Test-Header']; // "test-value"
Did you find this tutorial useful? Say thanks by starring our repo on GitHub!