Open In App

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

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:



Why use Fetch API?

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. 




<!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.




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.


Article Tags :