4
IntermediateDay 4: HTTP Server Basics
40 minutes2 examples
Progress
0%
Node.js has a built-in HTTP module that allows you to create web servers and make HTTP requests. This is the foundation for building web applications and APIs.
HTTP Module:
The http module provides functionality for creating HTTP servers and clients. It's a core module that doesn't need to be installed separately.
Creating a Server:
You can create an HTTP server using http.createServer() method. The server listens for requests and responds with appropriate data.
Request and Response Objects:
The server receives request objects containing information about the incoming request, and sends response objects back to the client.
Routing:
Basic routing involves checking the URL path and method to determine what response to send. You can handle different routes like GET, POST, PUT, DELETE.
Headers:
HTTP headers provide additional information about the request or response. Common headers include Content-Type, Content-Length, and custom headers.
Status Codes:
HTTP status codes indicate the result of the request. Common codes include 200 (OK), 404 (Not Found), 500 (Internal Server Error).
Error Handling:
Always handle errors gracefully in your HTTP server. Use try-catch blocks and proper error responses.
HTTP Module:
The http module provides functionality for creating HTTP servers and clients. It's a core module that doesn't need to be installed separately.
Creating a Server:
You can create an HTTP server using http.createServer() method. The server listens for requests and responds with appropriate data.
Request and Response Objects:
The server receives request objects containing information about the incoming request, and sends response objects back to the client.
Routing:
Basic routing involves checking the URL path and method to determine what response to send. You can handle different routes like GET, POST, PUT, DELETE.
Headers:
HTTP headers provide additional information about the request or response. Common headers include Content-Type, Content-Length, and custom headers.
Status Codes:
HTTP status codes indicate the result of the request. Common codes include 200 (OK), 404 (Not Found), 500 (Internal Server Error).
Error Handling:
Always handle errors gracefully in your HTTP server. Use try-catch blocks and proper error responses.
Interactive Examples
Basic HTTP Server
Creating a simple HTTP server with basic routing
JavaScript
const http = require('http');
const PORT = 3000;
const server = http.createServer((req, res) => {
  const method = req.method;
  const path = req.url;
  
  console.log(method + ' ' + path);
  
  // Set response headers
  res.setHeader('Content-Type', 'text/html; charset=utf-8');
  
  // Handle different routes
  if (path === '/' && method === 'GET') {
    res.statusCode = 200;
    res.end('<h1>Welcome to Node.js HTTP Server!</h1><p>This is the home page.</p>');
  } else if (path === '/about' && method === 'GET') {
    res.statusCode = 200;
    res.end('<h1>About Page</h1><p>This is the about page.</p>');
  } else if (path === '/api/users' && method === 'GET') {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify([
      { id: 1, name: 'John Doe', email: '[email protected]' },
      { id: 2, name: 'Jane Smith', email: '[email protected]' }
    ]));
  } else {
    res.statusCode = 404;
    res.end('<h1>404 - Page Not Found</h1><p>The requested page does not exist.</p>');
  }
});
server.listen(PORT, () => {
  console.log('Server running on http://localhost:' + PORT);
});Output
Server running on http://localhost:3000 GET / GET /about GET /api/users
Explanation
This example creates a basic HTTP server with routing for different pages and API endpoints. The server responds with HTML for pages and JSON for API routes.