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:
Importing Modules: The
http
module in Node.js is imported, which provides functionality to create an HTTP server.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.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
).Setting Response Headers:
res.writeHead()
is used to set the HTTP response status code to200
(which indicates a successful response) and set theContent-Type
header toapplication/json
to specify that the response will contain JSON data.Sending JSON Response:
JSON.stringify()
converts thejsonData
object to a JSON string, andres.end()
sends this JSON data as the response to any incoming HTTP request.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.