nodejs json data serving

Certainly! Below is an example of serving JSON data using Node.js:

// Import required modules
const http = require('http');

// Create sample JSON data
const jsonData = {
  name: 'John Doe',
  age: 30,
  email: '[email protected]'
};

// Create an HTTP server
const server = http.createServer((req, res) => {
  // Set response headers
  res.writeHead(200, { 'Content-Type': 'application/json' });

  // Convert JSON data to string and send it as the response
  res.end(JSON.stringify(jsonData));
});

// Listen on a specific port
const port = 3000;
server.listen(port, () => {
  console.log(`Server running on port ${port}`);
});

Explanation of steps:

  1. Importing Modules: The http module in Node.js is imported, which provides functionality to create an HTTP server.

  2. Creating JSON Data: A sample JSON object named jsonData is created. This data can be anything, and in this case, it contains name, age, and email information.

  3. Creating an HTTP Server: http.createServer() method is used to create an HTTP server. This method takes a callback function that handles incoming requests (req) and outgoing responses (res).

  4. Setting Response Headers: res.writeHead() is used to set the HTTP response status code to 200 (which indicates a successful response) and set the Content-Type header to application/json to specify that the response will contain JSON data.

  5. Sending JSON Response: JSON.stringify() converts the jsonData object to a JSON string, and res.end() sends this JSON data as the response to any incoming HTTP request.

  6. Listening on a Port: The server.listen() method is used to specify the port number (in this case, 3000) on which the server will listen for incoming requests. It also logs a message to the console indicating that the server is running on the specified port.

This code sets up a simple Node.js server that responds to any incoming HTTP requests with the specified JSON data.