In Node.js, handling HTTP requests and responses is a fundamental part of building web applications. You can use the built-in http
module or popular third-party libraries like Express.js to simplify the process. Below, I'll provide examples using both the native http
module and Express.js.
http
module:Creating a simple HTTP server:
javascriptconst http = require('http');
const server = http.createServer((req, res) => {
// Request handling logic
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Handling different HTTP methods and routes:
javascriptconst http = require('http');
const server = http.createServer((req, res) => {
// Routing
if (req.method === 'GET' && req.url === '/') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('Hello, World!\n');
} else if (req.method === 'GET' && req.url === '/about') {
res.writeHead(200, { 'Content-Type': 'text/plain' });
res.end('About us\n');
} else {
res.writeHead(404, { 'Content-Type': 'text/plain' });
res.end('Not Found\n');
}
});
const PORT = 3000;
server.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Installing Express:
bashnpm install express
Creating a simple Express server:
javascriptconst express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Handling different routes and HTTP methods with Express:
javascriptconst express = require('express');
const app = express();
const PORT = 3000;
app.get('/', (req, res) => {
res.send('Hello, World!');
});
app.get('/about', (req, res) => {
res.send('About us');
});
// Handling 404 Not Found
app.use((req, res) => {
res.status(404).send('Not Found');
});
app.listen(PORT, () => {
console.log(`Server running at http://localhost:${PORT}/`);
});
Both approaches are valid, and the choice between them depends on your project's complexity and requirements. Express.js is a popular choice for its simplicity and powerful features for building web applications.