axios.post headers example

axios.post headers example

If you are working with axios, you might need to send some headers with your post requests. Headers are used to send additional information about the request. For example, you might need to send an authorization token or specify the content type.

Here is an example of how to send headers with an axios.post request:


axios.post('/api/some-endpoint', {
    data: {
        // Your data here
    }
}, {
    headers: {
        'Authorization': 'Bearer ' + token,
        'Content-Type': 'application/json'
    }
})
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

In this example, we are making a post request to '/api/some-endpoint' with some data. We are also sending two headers with the request:

  • The 'Authorization' header with a value of 'Bearer ' + token. This header is used for authentication purposes.
  • The 'Content-Type' header with a value of 'application/json'. This header specifies that the data being sent is in JSON format.

Finally, we handle the response and error using the then() and catch() methods respectively.

Another way to send headers with axios.post is to use an object and spread operator:


const headers = {
    'Authorization': 'Bearer ' + token,
    'Content-Type': 'application/json'
};

axios.post('/api/some-endpoint', {
    data: {
        // Your data here
    }
}, { ...headers })
.then(function (response) {
    console.log(response);
})
.catch(function (error) {
    console.log(error);
});

In this example, we are creating an object called headers that contains the headers we want to send. We then spread this object into the third parameter of the axios.post method.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe