Lesson 12 of 30

HTTP Module

Chapter 12

HTTP Module

Learn how to create HTTP servers using the Node.js http module.

Theory

The http module allows Node.js applications to communicate using HTTP. It can be used to create web servers. The createServer() method creates an HTTP server. A server receives a request and sends a response. The server can listen on a specific port using listen().

Example

Node.js Example
const http = require("http");

const server = http.createServer(
  (req, res) => {
    res.writeHead(200, {
      "Content-Type": "text/plain"
    });

    res.end("Hello World");
  }
);

server.listen(3000);

Output

The HTTP server responds with Hello World.

Practice

Create an HTTP server that returns different messages for different URLs.

Interview Questions

1.

What is the Node.js http module?

2.

What does createServer() do?

3.

What is the purpose of listen()?

Quick Quiz

Which option best matches this chapter?

A.http
B.fs
C.path
D.os

Answer: http