Open In App

How to Replicate Postman POST API Request using AJAX ?

Last Updated : 01 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

In this project we’ll mimic the action of submitting data using POST to a server from a web page. We replicate this process using AJAX (Asynchronous JavaScript and XML) directly in a web page, we’re embedding similar functionality within our own interface. This involves setting up HTML elements like input fields and buttons to gather user input, using JavaScript to construct and send the request to the server, and handling the response accordingly.

Prerequisite

Approach to Replicate Postman POST API Request using AJAX

  • Setup HTML structure and define JavaScript Function.
  • Set up the XMLHttpRequest object with the appropriate details.
  • Construct the payload for your POST request.
  • Use the XMLHttpRequest’s send() method to send the POST request to the desired API endpoint.
  • Setting Up ExpressJS: The code initializes an Express.js server.
  • Define logic within the callback function to handle the response received from the server.

Steps to Create HTML project that replicates Postman POST API

Set Up Your HTML File (Frontend):

Create an HTML file with the name index.js. Add the below mentioned code in it.

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>POST Request Example</title>
</head>

<body>
    <input type="text" id="urlInput" placeholder="Enter API Endpoint URL">
    <button onclick="sendPostRequest()">Send POST Request</button>
    <div id="response"></div>

    <script>
        function sendPostRequest() {
            var xhr = new XMLHttpRequest();
            var url = document.getElementById("urlInput").value;
            xhr.open("POST", url, true);
            xhr.setRequestHeader("Content-Type", "application/json");

            xhr.onreadystatechange = function () {
                if (xhr.readyState === 4) {
                    if (xhr.status === 200 || xhr.status === 201) { // Handle both 200 and 201
                        // Handle the response data here
                        document.getElementById("response").innerText = xhr.responseText;
                    } else {
                        // Handle error response here
                        document.getElementById("response").innerText = 'Error: ' + xhr.status;
                    }
                }
            };

            var data = JSON.stringify({
                // Include your request payload here
                key1: 'value1',
                key2: 'value2'
            });

            xhr.send(data);
        }
    </script>
</body>

</html>

Run the HTML file

Test your implementation by opening the HTML file in a web browser.

output

Set up the Backend:

Step 1: Initialize a Node.js Project

  • Open your terminal.
  • Create a new project directory, Navigate to your project directory.
mkdir <<name of project>>
cd <<name of project>>

Run the following command to initialize a new Node.js project and create a package.json file:

npm init -y

Step 2: Install Dependencies

Run the following command to install the required dependencies (Express.js,cors):

npm install express cors

Step 3: Create index.js File

The index.js below sends request to the server using POST method. Let’s test this file using both Postman and our project.

Javascript
// index.js
const express = require('express');
const cors = require('cors');

const app = express();
const port = 5000;

app.use(cors()); // Enable CORS for all routes

const propertySchema = {
    name: String,
    description: String,
    numberOfRooms: Number,
    washroom: Number,
    kitchen: Boolean,
    hall: Boolean,
    amenities: [String]
};

// Temporary storage for properties
let properties = [
    {
        id: 1,
        name: "Luxury Beachfront Villa",
        location: "Malibu, California",
        room: 7,
        price: 1500000,
        amenities: ["Private Beach Access", "Infinity Pool", "Home Theater"]
    },
    {
        id: 2,
        name: "Charming Cottage",
        location: "Cotswolds, England",
        room: 3,
        price: 400000,
        amenities: ["Fireplace", "Garden", "Country Views"]
    },
    {
        id: 3,
        name: "Modern Downtown Loft",
        location: "New York City, New York",
        room: 2,
        price: 800000,
        amenities: ["City Views", "Gym", "Concierge Service"]
    },
    {
        id: 4,
        name: "Rustic Mountain Cabin",
        location: "Aspen, Colorado",
        room: 4,
        price: 600000,
        amenities: ["Hot Tub", "Ski-In/Ski-Out Access", "Wood-Burning Fireplace"]
    },
    {
        id: 5,
        name: "Paris Apartment",
        location: "Paris, France",
        room: 6,
        price: 2500000,
        amenities: ["Terrace", "Panoramic City Views", "24/7 Security"]
    },
    {
        id: 6,
        name: "Secluded Lakeside Retreat",
        location: "Lake District, England",
        room: 5,
        price: 1000000,
        amenities: ["Private Dock", "Boathouse", "Tranquil Surroundings"]
    }
];

// // Route to list properties
app.get('/properties', (req, res) => {
    res.json(properties);
});

// Route to create a new property
app.post('/properties', (req, res) => {
    const newProperty = req.body;
    properties.push(newProperty);
    res.status(201).json({ message: 'Property created successfully', property: newProperty });
});

app.listen(port, () => {
    console.log(`Server is running on port ${port}`);
});

Output of POST API in Postman

postmangif

output in Postmam

Output in POST API HTML file

ezgif-6-45f01e6ef7

output in index.js



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads