DEV Community

Emmanuelthadev
Emmanuelthadev

Posted on

How to make HTTP GET and POST requests in JavaScript using Axios

Axios is a popular, promise-based HTTP client that enables you to send HTTP requests using JavaScript. It has a simple API and can be easily integrated into your project.

In this article, we will look at how to make HTTP requests using Axios in JavaScript.

Installation
To use Axios in your project, you first need to install it using npm or yarn.

npm install axios
Enter fullscreen mode Exit fullscreen mode
yarn add axios
Enter fullscreen mode Exit fullscreen mode

Making a GET request
To make a GET request using Axios, you can use the get() method. The get() method takes in the URL of the endpoint as the first argument and an optional config object as the second argument.

Here is an example of making a GET request to the https://api.example.com/users endpoint:

const axios = require('axios');

axios.get('https://api.example.com/users')
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

In this example, we are sending a GET request to the https://api.example.com/users endpoint and logging the response data to the console. The then() method is called when the request is successful, and the catch() method is called when there is an error.

Making a POST request
To make a POST request using Axios, you can use the post() method. The post() method takes in the URL of the endpoint as the first argument and the data to be sent as the second argument. It also takes an optional config object as the third argument.

Here is an example of making a POST request to the https://api.example.com/users endpoint:

const axios = require('axios');

axios.post('https://api.example.com/users', {
    name: 'John Doe',
    email: 'john@example.com'
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

In this example, we are sending a POST request to the https://api.example.com/users endpoint with a payload containing the name and email of a user. The then() method is called when the request is successful, and the catch() method is called when there is an error.

Configuring request headers
You can configure the request headers by passing a config object as the second or third argument to the get() or post() method.

Here is an example of setting the Content-Type and Authorization headers in a POST request:

const axios = require('axios');

axios.post('https://api.example.com/users', {
    name: 'John Doe',
    email: 'john@example.com'
  }, {
    headers: {
      'Content-Type': 'application/json',
      'Authorization': 'Bearer abcdefghijklmnopqrstuvwxyz'
    }
  })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.log(error);
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)