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.
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
Contact Us