Node.js

HTTP Server

Build HTTP servers with Node.js using the built-in http module and the Express framework.

Built-in HTTP Module

Node.js includes a built-in http module for creating web servers. While lower-level than frameworks, understanding it helps you grasp how HTTP works.

const http = require('http');
const url = require('url');

const server = http.createServer((req, res) => {
  const { pathname, query } = url.parse(req.url, true);

  // Set response headers
  res.setHeader('Content-Type', 'application/json');
  res.setHeader('X-Powered-By', 'Node.js');

  // Simple routing
  if (pathname === '/api/hello' && req.method === 'GET') {
    res.writeHead(200);
    res.end(JSON.stringify({ message: 'Hello, World!' }));
  } else if (pathname === '/api/users' && req.method === 'GET') {
    const users = [
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' },
    ];
    res.writeHead(200);
    res.end(JSON.stringify(users));
  } else {
    res.writeHead(404);
    res.end(JSON.stringify({ error: 'Not Found' }));
  }
});

server.listen(3000, () => {
  console.log('Server running at http://localhost:3000');
});

Express.js Framework

Express is the most popular Node.js web framework. It simplifies routing, middleware, and request/response handling.

import express, { Request, Response, NextFunction } from 'express';

const app = express();

// Middleware
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

// CORS middleware
app.use((req: Request, res: Response, next: NextFunction) => {
  res.setHeader('Access-Control-Allow-Origin', '*');
  res.setHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE');
  res.setHeader('Access-Control-Allow-Headers', 'Content-Type, Authorization');
  next();
});

// Routes
app.get('/api/users', async (req: Request, res: Response) => {
  const { page = 1, limit = 10 } = req.query;
  // Fetch users from DB...
  res.json({ users: [], page: Number(page), limit: Number(limit) });
});

app.get('/api/users/:id', (req: Request, res: Response) => {
  const { id } = req.params;
  res.json({ id, name: 'Alice' });
});

app.post('/api/users', async (req: Request, res: Response) => {
  const { name, email } = req.body;
  const newUser = { id: Date.now(), name, email };
  res.status(201).json(newUser);
});

// Error handler
app.use((err: Error, req: Request, res: Response, next: NextFunction) => {
  console.error(err.stack);
  res.status(500).json({ error: err.message });
});

app.listen(3000, () => console.log('Server on http://localhost:3000'));