How to use Axios in Node.js

axios is promise based HTTP client for the browser and node.js, which makes dealing with HTTP request very easy. In this tutorial we will see how to use axios for GET, POST, UPDATE and DELETE requests in node.js

Below is the set up before starting this tutorial

  • Operating System : Windows 10
  • VS Code IDE
  • Node Version : v12.13.0
  • NPM Version : 6.12.0

  • Create a directory with name test-axios and open this directory with vs code.
  • Open new terminal in vs code and run below command
  • 
    npm init -y
    
    

  • Install axios with below command
  • 
    npm install axios
    
    

  • Create a file inside axiosDemo.js inside test-axios
  • Now we have set up ready with axios for making HTTP request, we will use JSONPlaceholder for getting dummy API to use with axios, same code can be used with real API as well , for the demo purpose JSONPlaceholder will also work.

    Make GET request with axios in node.js
    write below code in axiosDemo.js and excute command node axiosDemo.js in terminal.

    
    const axios = require('axios');
    
    const url = "https://jsonplaceholder.typicode.com/posts"
    
    const getData = async () => {
    
        const response = await axios.get(url)
        console.log(response.data)
    
    }
    getData()
    
    
    

    You should see below output

    
    [
      {
        userId: 1,
        id: 1,
        title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit',
        body: 'quia et suscipit\n' +
          'suscipit recusandae consequuntur expedita et cum\n' +
          'reprehenderit molestiae ut ut quas totam\n' +
          'nostrum rerum est autem sunt rem eveniet architecto'
      },
      {
        userId: 1,
        id: 2,
        title: 'qui est esse',
        body: 'est rerum tempore vitae\n' +
          'sequi sint nihil reprehenderit dolor beatae ea dolores neque\n' +
          'fugiat blanditiis voluptate porro vel nihil molestiae ut reiciendis\n' +
          'qui aperiam non debitis possimus qui neque nisi nulla'
      },
      {
        userId: 1,
        id: 3,
        title: 'ea molestias quasi exercitationem repellat qui ipsa sit aut',
        body: 'et iusto sed quo iure\n' +
          'voluptatem occaecati omnis eligendi aut ad\n' +
          'voluptatem doloribus vel accusantium quis pariatur\n' +
          'molestiae porro eius odio et labore et velit aut'
     .....
     ]
    
    

    Make POST request with axios in node.js
    write below code in axiosDemo.js and excute command node axiosDemo.js in terminal.

    
    
    const axios = require('axios');
    
    const url = "https://jsonplaceholder.typicode.com/posts"
    
    
    const payload = 
        {
            "userId": 1,
            "id": 1,
            "title": "test",
            "body":"testing"
          }
      
    
    const postData = async () => {
        try {
        const response = await axios.post(url, payload)
        console.log(response.status)
        console.log(response.data)
        } catch (error){
            console.log(error)
            
        }
    
    }
    postData()
    
    

    You should see below output

    
    201
    { userId: 1, id: 101, title: 'test', body: 'testing' }
    

    Make PUT request with axios in node.js
    write below code in axiosDemo.js and excute command node axiosDemo.js in terminal.

    
    const axios = require('axios');
    
    const url = "https://jsonplaceholder.typicode.com/posts/1"
    
    
    const payload = {
        "userId": 1,
        "id": 1,
        "title": "update request",
        "body": "update request"}
      
    
    const updateData = async () => {
        try {
        const response = await axios.put(url, payload)
        console.log(response.status)
        console.log(response.data)
        } catch (error){
            console.log(error)
            
        }
    
    }
    updateData()
    
    
    

    You should see below output

    
    200
    { userId: 1, id: 1, title: 'update request', body: 'update request' }
    

    Make DELETE request with axios in node.js
    write below code in axiosDemo.js and excute command node axiosDemo.js in terminal.

    
    const axios = require('axios');
    
    const url = "https://jsonplaceholder.typicode.com/posts/1" 
    
    const deleteData = async () => {
        try {
        const response = await axios.delete(url)
        console.log(response.status)
        console.log(response.data)
        } catch (error){
            console.log(error)
            
        }
    
    }
    deleteData()
    
    
    

    You should see below output

    
    200
    {}
    

    Category: WebDev