How to handle HTTP requests and responses in Node.js



Image not found!!

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.

Using the native http module:

  1. Creating a simple HTTP server:

    javascript
    const 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}/`); });
  2. Handling different HTTP methods and routes:

    javascript
    const 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}/`); });

Using Express.js:

  1. Installing Express:

    bash
    npm install express
  2. Creating a simple Express server:

    javascript
    const 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}/`); });
  3. Handling different routes and HTTP methods with Express:

    javascript
    const 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.