Open In App

How to post JSON data to Server ?

Improve
Improve
Like Article
Like
Save
Share
Report

JSON is an abbreviation for Javascript Object Notation. JSON is a text-based data format used to store and convey information. It is widely used to transfer data from the server to the client, the client to the server, and the server to the server.

Syntax: The key/value pairs in JSON are separated by commas:

{
    "name": "David",
    "age": 22,
    "gender": "male",
}

Setup and Installation:

Step 1: Create a folder called PostJSON and run the following command to launch a NodeJS application.

npm init -y 

Step 2: Using the following command, install the required npm packages.

npm install express body-parser

Step 3: Create index.html and server.js files in your project directory.

Project Structure: Our project directory should now look like this:

 

Step 4: Require and configure the express app so that it can start listening for requests. Our server is configured to use Port 3000.

Javascript




const express = require("express");
const bodyParser = require("body-parser");
const app = express();
app.use(express.json());
 
app.get("/", function (req, res) {
    res.sendFile(__dirname + "/index.html");
});
 
app.post("/data", function (req, res) {
    console.log(req.body.name);
    console.log(req.body.email);
});
 
app.listen(3000, function () {
    console.log("Server started on port 3000");
});


The Frontend structure of our application is simple, with two inputs: one for name and one for email. A send button for sending the input data to the server. When the user hits the send button it makes a POST request with JSON data to the /data route on the server, and then the server logs the received data.

Example 1: In this example, we will make use of fetch API to send data to the NodeJS server.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Post JSON to Server</title>
    <script>
        function send() {
            var name = document.getElementById("name").value;
            var email = document.getElementById("email").value;
            var result = document.getElementById("result");
           
              const json = {
                  name: name,
                  email: email,
            };
 
            fetch("/data", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json",
                },
                body: JSON.stringify(json),
            });
        }
    </script>
</head>
 
<body>
    <h1 style="color: green">Welcome To GFG</h1>
    <input type="text" id="name" placeholder="Name" />
    <input type="email" id="email" placeholder="Email" />
    <button onclick="send()">Send</button>
</body>
 
</html>


Output:

 

Example 2: The following example shows how we can use XMLHttpRequest (XHR) to make a JSON POST request.

HTML




<!DOCTYPE html>
<html>
 
<head>
    <title>Post JSON to Server</title>
    <script>
        function send() {
            var name = document.getElementById("name").value;
            var email = document.getElementById("email").value;
            var result = document.getElementById("result");
 
            const xhr = new XMLHttpRequest();
 
            // create a JSON object
            const json = {
                name: name,
                email: email,
            };
 
            // open request
            xhr.open("POST", "/data");
 
            // set `Content-Type` header
            xhr.setRequestHeader("Content-Type",
                                 "application/json");
 
            // send request with JSON payload
            xhr.send(JSON.stringify(json));
        }
    </script>
</head>
 
<body>
    <h1 style="color: green">Welcome To GFG</h1>
    <input type="text" id="name" placeholder="Name" />
    <input type="email" id="email" placeholder="Email" />
    <button onclick="send()">Send</button>
</body>
 
</html>


Output:

 

Steps to run the application:

Step 1: Start the server with the help of the following command.

node server.js

Step 2: Type the following URL in your browser and you will see the index.html page displaying contents.

http://localhost:3000/

Step 3: Type the name and email in the input boxes and click on the send button.

Step 4: Check the terminal whether the server logs the received data or not. 



Last Updated : 01 Aug, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads