Home / Snippets / How to make an Axios POST request
How to make an Axios POST request cover

How to make an Axios POST request

1.6K

3 years ago

0 comments

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!
notion avatar

Alaz

Week-end developer currently experimenting with web, mobile, and all things programming.

Topics:

Frontend

Resource

Average

Average

Support Us

If you like our tutorial, support us by being our Patreon or buy us some coffee ☕️

Welcome to PostSrc V3

PostSrc Dark Logo

You have to login to favorite this