Open In App

How to Generate/Send JSON Data at the Client Side ?

Last Updated : 25 Mar, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Javascript Object Notation (JSON) is a widely used format for sending and receiving data to or from the server. In this article, we will use fetch API to send and receive data from the NodeJS server. 

Advantages of JSON:

  • Because of its easy and small syntax, it executes the response in a faster way.
  • It is supported by a wide range of browsers.
  • Parsing at the server-side using JSON is very fast.
  • It is the most suitable format for transferring data of any size. This is due to the fact that JSON stores data in arrays, which makes it easier to transmit.

Why use Fetch API?

  • The Fetch API is a modern method that allows web browsers to send HTTP requests to servers.
  • It is similar to XMLHttpRequest but a lot simpler and clearer.
  • It makes use of Javascript Promises to give more customizable choices for making server requests from web browsers.

Setup and Installation

Step 1: Create a folder named SendDataToClient and run the following command to initiate a NodeJS application.

npm init -y 

Step 2: Install the necessary npm packages using the following command.

npm install express body-parser

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

Project Structure: Now, our project directory will look like this.

Frontend Code: The structure is straightforward, with two inputs: one for name and one for email. A send button to send the input data to the server and an empty paragraph to display the server’s JSON response. 

index.html




<!DOCTYPE html>
<html>
<head>
<title>Send data to client</title>
<script>
    function sendData() {
        var name = document.getElementById("name").value;
        var email = document.getElementById("email").value;
        var result = document.getElementById("result");
        
        fetch("/jsondata", {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
          },
          body: JSON.stringify({ name: name, email: email }),
        })
          .then(function (response) {
            return response.json();
          })
          .then(function (data) {
            result.innerHTML = data.msg;
          })
          .catch(function (error) {
            console.log(error);
          });
    }
</script>
</head>
<body>
    <h1 style="color: green">GFG</h1>
    <input type="text" id="name" placeholder="Your name" />
    <input type="email" id="email" placeholder="Email" />
    <button onclick="sendData()">Send</button>
    <p id="result" style="color: orange"></p>
  
</body>
</html>


Backend Code: The Express framework with NodeJS is used to build the server, which runs on port 3000. Whenever the user clicks on send button it sends a POST request containing JSON data on /jsondata route and then the server responded with a JSON reply.

server.js




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("/jsondata", function (req, res) {
    res.json({ msg: `Hello ${req.body.name}, your email is ${req.body.email}` });
});
  
app.listen(3000, function () {
    console.log("Server started on port 3000");
});


Steps to Run the Application: To run the application using the following command:

node server.js

Output: Go to http://localhost:3000/ to see the output screen.



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads