Posts Learn Components Snippets Categories Tags About
/

How to make an Axios POST request

Learn how to make a POST request in Axios HTTP Client the easy way. Get to know how to pass headers and body data in Axios.

Created on Aug 27, 2021

93 views

What is Axios HTTP Client?

Axios is a promise-based HTTP client for the front-end applications and the node.js backend. It's a very simple and easy-to-use library that many front-end applications depend on to call an external API.

How to install Axios?

To add Axios into your project you can use npm or yarn package manager. If you have not done so do run the command below.
npm install axios
yarn add axios
Otherwise, you can just include the CDN scripts below and you can right away make use of the library.
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

POST Request in Axios Code Example


To perform a POST request you can make use of the "post" method available from the "axios" object. Do also note that Axios is a promise-based library so it supports async/await syntax.
<script>
    import axios from 'axios';

    const response = await axios
        .post('https://jsonplaceholder.typicode.com/posts', {
            title: 'foo',
            body: 'bar',
            userId: 1,
        }, {
            headers: { 'Content-type': 'application/json; charset=UTF-8' }
        });

    console.log(response);
</script>
In the case of the code example above, we will be using "jsonplaceholder.typicode.com" as the "fake API for testing".
https://jsonplaceholder.typicode.com/posts

Axios POST Body Data


To specify the body data you can pass in an object of values as the second parameter.
const data = {
    title: 'foo',
    body: 'bar',
    userId: 1,
}

axios.post('your-url-here', data);

Axios POST Headers Configuration

To define header configuration for your POST method, you can pass it in as the 3rd parameter. Do refer the code below.
axios.post('your-url-here', 'your-data-here', {
    headers: { 'Content-type': 'application/json; charset=UTF-8' }
});

Axios POST with "then" method


To retrieve the response through the "then" keyword you can write your code like below. By making use of this keyword you won't have to use the "async" and "await" anymore.
axios
    .post('your-url', 'your-data', 'your-headers')
    .then((data) => console.log(data))
By now you should know How to make an Axios POST request, If you find it helpful do share it with your friends, and happy coding!

Snippets by

PostSrc poster

PostSrc

Full stack developer mainly focusing on the front end side of the web. The main author of PostSrc and loves writing tutorial and guides online.

Load comments for How to make an Axios POST request

new

PostSrc Code Components

Collection of Tailwind CSS components for everyone to use. Browse all of the components that's right for your project.

View Components

Other Code Snippets

More