How to use HTTP interface In NodeJS

Although the first method is sufficient for most solutions, there is another method that uses HTTP interface by Node.js and returns JSON data. Node.js comes with an in-built HTTP module, so we won’t have to install it separately as we did for express.

Step 1: Making HTTP ready for use

We need to require HTTP in our server to be able to use it. This can be done simply by adding the code below to our server.

const http = require('http');

Step 2: Using http and JSON.stringify() to return JSON data

We will now use http.createServer() and JSON.stringify() to return JSON data from our server.

Example: Implementation to show returning the JSON data in nodeJS using above method.

index.js
const http = require('http');

const app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ number: 1 , name: 'John'}));
});

app.listen(3000);

Step to Run Application: Run the application using the following command from the root directory of the project

node index.js

Output: Your project will be shown in the URL http://localhost:3000/

Note: Both the methods can be used for returning JSON data from the server and both will produce the same output.

How to Return JSON using Node.js ?

Node.js is a powerful platform for building server-side applications and returning JSON data is a common task in web development, especially when building APIs. JSON stands for JavaScript Object Notation. It is one of the most widely used formats for exchanging information across applications. Node.js supports various frameworks that help to make the processes smoother. The following ways cover how to return JSON data in our application from Node.js. This article will guide you through the process of setting up a simple Node.js server that returns JSON data in response to client requests.

Table of Content

  • Using ExpressJS
  • Using HTTP interface

Similar Reads

Using ExpressJS

Express is a back end web application framework for Node.js. It is one of the standard frameworks which many developers use. To install it, we will be using NPM (Node Package Manager)....

Using HTTP interface

Although the first method is sufficient for most solutions, there is another method that uses HTTP interface by Node.js and returns JSON data. Node.js comes with an in-built HTTP module, so we won’t have to install it separately as we did for express....

Conclusion

Returning JSON data in a Node.js application is straightforward using the Express framework. By following this guide, you can set up a simple server that responds with JSON data and expand it to handle dynamic data and multiple routes. This forms the basis for building robust APIs and web services with Node.js....

Contact Us