How to send JSON response using Node.js ?
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.
Project structure: Now our directory structure will look like the following.
- Import the HTTP module with require keyword at the top of the app.js file, and store that returned result in a const variable.
- 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
- Now call the function listen() by providing the port number, hostname, and callback function.
- The callback function will get executed either on the successful start of the server or on a failure.
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.
- The first console.log() statement is just to indicate that our server is working and the request listener is being called on any request.
- Next, we are preparing some random data to send as a response.
Step 5: Now we will send the response. The data will be sent along with the response object to the user.
- 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.
- Finally, we have passed the request listener inside createServer(), so that each request to the server can call this functionality inside the request listener.
Step to run the application: Open the terminal and type the following command.
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.