Node JS Tutorial - Serving JSON Data
In this tutorial, we will learn how to serve JSON data to clients using Node.js.
Step 1: Create a Server in Node.js
Go to your project and open the index.js file. First, require the http package and write the following code:
var http = require('http');
var server = http.createServer(function(req,res)
{
res.writeHead(200,{'Content-Type':'application/json'});
var student = {
name:"Jenifer",
email:"jenifer@gmail.com",
phone:"1234567890",
age:25.
};
res.end(JSON.stringify(student));
});
server.listen(3000);
console.log("Server is running on localhost:3000");
Step 2: Run the Server
Next, let's run the server. Go to the command prompt and execute the following command:
node index.js
The server is now running on localhost:3000. Open a web browser and navigate to localhost:3000. You should see the JSON data being served by the server.
That's it! You have successfully served JSON data to a client using Node.js. This is a fundamental concept in web development, and is used extensively in APIs and web applications.
By following these simple steps, you can easily serve JSON data to clients using Node.js.