Open In App

How to send JSON response using Node.js ?

Last Updated : 15 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

NodeJS is the runtime environment, which can execute the javascript code on any platform. It is widely used to create and run web application servers because of its salient features. During production, several times we need to send the resources or some type of information as a response, and javascript object notation (JSON) syntax is widely used to send data also it is used for communication between any two applications. In this article, we are going to see how we can send information to the user as JSON through a node.js server. NodeJS contains an inbuilt HTTP module, it is used to transfer data over the HTTP protocol and supports many features that are useful for any web application.

Let’s see the step-by-step implementation.

Step 1: Create a NodeJS application

Write this command in your terminal and it will create a node application. This command will also ask for few configurations for this application which is quite simple to provide. As another option, you can use the -y flag after npm init for default configurations.

npm init

Step 2: Create a Javascript file and we are going to name it app.js you can name whatever you want. In this file, we will write our entire code.

Project structure: Now our directory structure will look like the following.

Step 3: Now we are going to create a backend server, more clearly creating a server is nothing but writing few lines of code and calling the inbuilt functions of nodejs. It just creates a runtime that executes javascript code on the machine.

Approach:

  1. Import the HTTP module with require keyword at the top of the app.js file, and store that returned result in a const variable.
  2. Now call the createServer() function, it will provide you a web server in return. Later this server object will be used to listen the connection on a specified host and port
  3. Now call the function listen() by providing the port number, hostname, and callback function.
  4. The callback function will get executed either on the successful start of the server or on a failure.

app.js




const http = require('http');
 
const server = http.createServer();
 
server.listen(3000,'localhost', function(error){
    if(!error)
        console.log("Server is Listening at Port 3000!");
    else
        console.log("Error Occurred");
});


Output: Use the node app.js command in your terminal to run the server. Something like this will be shown in your terminal on successful start.

Step 4: Create a Request Listener. Till step 3 we have successfully created a server but currently, the server will neither interact with us nor respond to our request. The reason is we have not created the request listeners yet. In this step we are going to create a request listener, this gets called every time someone hits on the server.

Approach:

  1. Create a simple function as we do in javascript, and this function will receive the request and response object as a parameter, and we can perform any server-related functionalities inside this.
  2. The first console.log() statement is just to indicate that our server is working and the request listener is being called on any request.
  3. Next, we are preparing some random data to send as a response.

app.js




const requestListener = (req, res)=>{
  console.log("Request is Incoming");
   
  const responseData = {
      message:"Hello, GFG Learner",
    articleData:{
        articleName: "How to send JSON response from NodeJS",
        category:"NodeJS",
        status: "published"
    },
    endingMessage:"Visit Geeksforgeeks.org for more"
  }
};


Step 5: Now we will send the response. The data will be sent along with the response object to the user. 

Approach:

  1. Inside the requestListener before sending a response, we are creating a jsonContent from a javascript object because the end() function which will be used to send data, receives either a buffer or string as data.
  2. The JSON.stringify() is the inbuilt method in nodejs it accepts a javascript object and returns the stringified object.
  3. The call to end() function indicates to the server that all processes have been finished so that it can send the response to the user.
    The end function can receive data to be sent along with the response, callback function which gets called when the response stream finishes successfully, and character encoding.
    In our case, we are only interested in sending the data.
  4. Finally, we have passed the request listener inside createServer(), so that each request to the server can call this functionality inside the request listener.

app.js




const http = require('http');
 
const requestListener = (req, res)=>{
  console.log("Request is Incoming");
     
  const responseData = {
      message:"Hello, GFG Learner",
    articleData:{
        articleName: "How to send JSON response from NodeJS",
        category:"NodeJS",
        status: "published"
    },
    endingMessage:"Visit Geeksforgeeks.org for more"
  }
   
  const jsonContent = JSON.stringify(responseData);
  res.end(jsonContent);
};
 
const server = http.createServer(requestListener);
 
server.listen(3000,'localhost', function(){
    console.log("Server is Listening at Port 3000!");
});


Step to run the application: Open the terminal and type the following command.

node app.js

Output: This is the JSON response of the request. If we open the network section of the chrome developers tool we will be able to see the actual response from the server.

So that was all about sending responses as JSON from the NodeJS server. 



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

Similar Reads