Thuta Learning
IntermediateWeb Developmentbeginner

HTTP Module

Relax. We'll talk through this in plain words — no textbook voice.

http is Node.js's built-in module that lets it act as a web server, accepting requests and sending back responses. Before you reach for Express.js, this module is the best foundation for understanding the HTTP request/response flow.

javascript
const http = require('http');

const server = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'text/html; charset=utf-8');

  if (req.url === '/') {
    res.statusCode = 200;
    res.end('<h1>Home Page</h1><p>Welcome to Node.js.</p>');
  } else if (req.url === '/about') {
    res.statusCode = 200;
    res.end('<h1>About Page</h1><p>This page is served by Node.js.</p>');
  } else {
    res.statusCode = 404;
    res.end('<h1>404 Not Found</h1>');
  }
});

server.listen(5000, () => {
  console.log('Server is listening on http://localhost:5000');
});

req.url shows the path the user requested. / returns the home page, and /about returns the about page. If nothing matches, it returns a 404 status code with a not-found message.

You should see
Server is listening on http://localhost:5000 Browser: http://localhost:5000/about About Page

Info

Returning the correct status code matters a lot for API/web server quality. Use 200 for success, 201 for created, 404 for not found, and 500 for server errors, and so on.

Easy traps

  • If you forget to call res.end(), the request never finishes and the browser may just keep loading.

Exercise

Express.js is built on top of these HTTP concepts to make things easier. Once you understand this lesson, you'll pick up Express routing that much faster.

You'll know it worked when: