
Node.js provides a built-in HTTP module that allows developers to create web servers and handle HTTP requests and responses efficiently. This article explores how to build a simple HTTP server, handle requests and responses, work with query parameters and headers, and serve static files.
1. Creating a Simple HTTP Server
Node.js enables developers to create a web server using the http
module. Below is a simple example:
const http = require('http'); const server = http.createServer((req, res) => { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello, World! Welcome to my Node.js server.'); }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Explanation:
- The
http.createServer()
method creates an HTTP server. - The callback function handles requests and responses.
res.writeHead(200, { 'Content-Type': 'text/plain' })
sets the status code and response headers.res.end('Hello, World!')
sends the response body.server.listen(PORT, callback)
starts the server on port 3000.
2. Handling Requests and Responses
Handling different types of requests (GET, POST, etc.) is essential in web servers. Below is an improved version of our server that processes requests differently based on the URL and HTTP method:
const http = require('http'); const server = http.createServer((req, res) => { if (req.method === 'GET' && req.url === '/') { res.writeHead(200, { 'Content-Type': 'text/html' }); res.end('<h1>Welcome to the Home Page</h1>'); } else if (req.method === 'POST' && req.url === '/data') { let body = ''; req.on('data', chunk => { body += chunk.toString(); }); req.on('end', () => { res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Data received', data: body })); }); } else { res.writeHead(404, { 'Content-Type': 'text/plain' }); res.end('404 Not Found'); } }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Explanation:
- If the request is GET and URL is
/
, it returns an HTML response. - If the request is POST to
/data
, it processes the incoming data and returns it as JSON. - If the request does not match any route, it returns a
404 Not Found
response.
3. Working with Query Parameters and Headers
Query parameters allow data to be sent via the URL, and headers provide metadata about the request. Here's how to handle them:
const url = require('url'); const http = require('http'); const server = http.createServer((req, res) => { const parsedUrl = url.parse(req.url, true); const queryParams = parsedUrl.query; const headers = req.headers; res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(JSON.stringify({ message: 'Query Parameters and Headers', queryParams, headers })); }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Explanation:
- The
url.parse(req.url, true)
method extracts query parameters. req.headers
retrieves request headers.- The response returns a JSON object with the extracted data.
Example Request:
GET http://localhost:3000/?name=John&age=30
Example Response:
{ "message": "Query Parameters and Headers", "queryParams": { "name": "John", "age": "30" }, "headers": { "host": "localhost:3000", "user-agent": "Mozilla/5.0" } }
4. Serving Static Files
A Node.js server can also serve static files such as HTML, CSS, and images using the fs
module.
const http = require('http'); const fs = require('fs'); const path = require('path'); const server = http.createServer((req, res) => { let filePath = path.join(__dirname, 'public', req.url === '/' ? 'index.html' : req.url); let extname = path.extname(filePath); let contentType = 'text/html'; switch (extname) { case '.js': contentType = 'text/javascript'; break; case '.css': contentType = 'text/css'; break; case '.json': contentType = 'application/json'; break; case '.png': contentType = 'image/png'; break; case '.jpg': contentType = 'image/jpg'; break; } fs.readFile(filePath, (err, content) => { if (err) { if (err.code === 'ENOENT') { res.writeHead(404, { 'Content-Type': 'text/html' }); res.end('<h1>404 Not Found</h1>'); } else { res.writeHead(500); res.end(`Server Error: ${err.code}`); } } else { res.writeHead(200, { 'Content-Type': contentType }); res.end(content, 'utf8'); } }); }); const PORT = 3000; server.listen(PORT, () => { console.log(`Server is running on http://localhost:${PORT}`); });
Explanation:
- Uses
fs.readFile()
to serve static files. - Determines the correct
Content-Type
based on file extension. - If the file does not exist, it returns a
404 Not Found
page.
Conclusion
The Node.js HTTP module is a powerful tool for creating web servers. This guide covered:
- Creating a simple HTTP server.
- Handling requests and responses.
- Working with query parameters and headers.
- Serving static files.
By mastering these concepts, you can build robust Node.js applications that handle various web requests efficiently.
Leave a Comment