Skip to content

Working with HTTP

The http module allows our application to listen for incoming requests and send back responses.

Fundamentally, this is all a web server does: Listen for a request → Do something → Send a response.


We create a server by calling http.createServer(). This method takes a callback function that runs every time a request hits the server.

  • req (Request): Contains details about the incoming request (URL, Headers, Data).
  • res (Response): Used to send data back to the client (Status, Headers, Body).

Let’s build a minimalist server that replies with plain text.

'use strict';
// 1. Load the core 'http' module
const http = require('http');
// 2. Define the hostname and port
const hostname = '127.0.0.1'; // Localhost
const port = 3000;
// 3. Create the Server
// The callback runs EVERY time a request hits the server
const server = http.createServer((req, res) => {
// A. Set the status (200 OK)
res.statusCode = 200;
// B. Set the Content-Type header
// "text/plain" means we are sending simple text, not HTML
res.setHeader('Content-Type', 'text/plain');
// C. Send the body and close the connection
res.end('Hello Node Server!');
});
// 4. Start listening
server.listen(port, hostname, () => {
console.log(`Server running at http://${hostname}:${port}/`);
});

[!TIP] Try it out!

  1. Run the script: node server.js (or whatever you named it).
  2. Go to http://localhost:3000 in your browser.
  3. Micro-Challenge: Change the res.end message to something else and restart the server. Notice you have to restart it to see changes? (Unless you use nodemon from the previous lesson!)

The Request-Response Cycle


Basic HTTP Server Demo Repo

Node.js HTTP Docs

Our server file works, but it’s getting a bit crowded. As our application grows, we can’t keep everything in one file.

It’s time to organize our code by modularizing it.

Loading Modules (CommonJS)