Loading lesson path
Formula
Node.js includes a powerful built - in HTTP module that enables you to create HTTP servers and make HTTP requests.This module is essential for building web applications and APIs in Node.js.
Create HTTP servers to handle requests and send responses
Handle different HTTP methods (GET, POST, PUT, DELETE, etc.)To use the HTTP module, include it in your application using the require() method: // Using CommonJS require (Node.js default)
const http = require('http');Formula
// Or using ES modules (Node.js 14 + with "type": "module" in package.json)// import http from 'http';method creates an HTTP server that listens for requests on a specified port and executes a callback function for each request.
// Import the HTTP module const http = require('http');
// Create a server object const server = http.createServer((req, res) => {Formula
// Set the response HTTP header with HTTP status and Content type res.writeHead(200, { 'Content - Type': 'text/plain' });// Send the response body as 'Hello, World!'
res.end('Hello, World!\n');
});
// Define the port to listen on const PORT = 3000;
// Start the server and listen on the specified port server.listen(PORT, 'localhost', () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Understanding the Code http.createServer()Save the code in a file named server.js Run the server using Node.js: node server.js Visit http://localhost:3000 in your browser to see the response.
HTTP headers let you send additional information with your response.
The res.writeHead()method is used to set the status code and response headers.
Example: Setting Multiple Headers const http = require('http');
const server = http.createServer((req, res) => {
// Set status code and multiple headers res.writeHead(200, {Formula
'Content - Type': 'text/html',
'X - Powered - By': 'Node.js',
'Cache - Control': 'no - cache, no - store, must - revalidate','Set-Cookie': 'sessionid=abc123; HttpOnly'
});
res.end('<h1>Hello, World!</h1>');
});
server.listen(3000, () => {
console.log('Server running at http://localhost:3000/');
});200 OK
201
Request has been fulfilled and new resource created 301
Resource has been moved to a new URL 400
Server cannot process the request due to client error 401
403
404