JavaScript

HTTP POST Request in Node using Axios

Hello. In this tutorial, we will understand and see a practical implementation of the HTTP POST Request with Axios in the express js application.

1. Introduction

Axios is a promise-based HTTP client for browser and nodejs. It makes asynchronous calls to the restful endpoints and can be used with plain javascript or applications like Vue or React. It offers several features like –

  • Making XMLHttpRequests from the browser
  • Making http requests from nodejs
  • Supports Promise api
  • Can intercept request and response
  • Can transform request and response data
  • Can cancel requests
  • Supports automatic transformation for json data
  • Offers protection against xsrf attacks

1.1 Setting up Node.js

To set up Node.js on windows you will need to download the installer from this link. Click on the installer (also include the NPM package manager) for your platform and run the installer to start with the Node.js setup wizard. Follow the wizard steps and click on Finish when it is done. If everything goes well you can navigate to the command prompt to verify if the installation was successful as shown in Fig. 1.

Fig. 1: Verifying node and npm installation

2. HTTP POST Request in Node using Axios

To set up the application, we will need to navigate to a path where our project will reside and I will be using Visual Studio Code as my preferred IDE.

2.1 Setting up dependencies

Navigate to the project directory and run npm init -y to create a package.json file. This file holds the metadata relevant to the project and is used for managing the project dependencies, script, version, etc. Replace the generated file with the code given below –

package.json

{
  "name": "nodejs-axios",
  "version": "1.0.0",
  "description": "Using axios in nodejs and expressjs",
  "main": "index.js",
  "scripts": {
    "dev": "nodemon index.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [
    "axios",
    "nodejs",
    "expressjs",
    "nodemon"
  ],
  "author": "geeks",
  "license": "MIT",
  "devDependencies": {
    "nodemon": "^2.0.15"
  },
  "dependencies": {
    "axios": "^0.26.1",
    "ejs": "^3.1.7",
    "express": "^4.17.3"
  }
}

Once the file is replaced trigger the below npm command in the terminal window to download the different packages required for this tutorial.

Downloading dependencies

npm install

2.2 Setting up the implementation file

Create a file responsible to describe the implementation. The file will be responsible to make the Axios http get call to fetch all posts and an individual post.

index.js

const express = require("express");
const axios = require("axios");
const app = express();

const url = "https://jsonplaceholder.typicode.com/posts";

// url - http://localhost:2410/
app.get("/", async (req, res) => {
  try {
    console.log("Making axios call");
    const response = await axios.get(url);
    res.status(200).json({ data: response.data });
  } catch (err) {
    console.log(err);
    res.status(500).json({ msg: "something bad has occurred." });
  }
});

// url - http://localhost:2410/1
app.get("/:id", async (req, res) => {
  try {
    let postId = req.params.id;
    console.log("Making axios call with post id= " + postId);
    const response = await axios.get(url + "/" + postId);
    res.status(200).json({ data: response.data });
  } catch (err) {
    console.log(err);
    res.status(500).json({ msg: "something bad has occurred." });
  }
});

// driver code
const port = 2410;
app.listen(port, () =>
  console.log(`app is listening on : http://localhost:${port}`)
);

3. Run the Application

To run the application navigate to the project directory and enter the following command as shown below in the terminal.

Run command

$ npm run dev

If everything goes well the application will be started successfully at the service endpoint – http://localhost:2410

4. Application endpoints

The application exposes the below endpoints that you can explore in the browser to understand the jade implementation.

Application endpoints

// application endpoint

// http get - http://localhost:2410/

// http get - http://localhost:2410/1

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

5. Summary

In this tutorial, we saw the Axios theory and a very basic practical implementation in an express js application. You can download the source code from the Downloads section.

6. Download the Project

This was a tutorial to implement the HTTP POST Request with Axios Axios in a node.js and express js application.

Download
You can download the full source code of this example here: HTTP Request in Node using Axios

Yatin Batra

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back to top button