2 Hours

5. HTTP Module: Creating a Server

Networking

What is an HTTP Server?

An HTTP server listens for requests from web browsers and sends back responses. Every website you visit is served by an HTTP server. Node.js has a built-in http module that lets you create one in just a few lines of code.

Creating Your First Server

The http.createServer() method creates a server. It takes a callback function that runs every time a request arrives. The callback receives two objects: req (the request) and res (the response). You then send a response using res.end().

JavaScript
const http = require('http');

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

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

Try it: Run this code. Open your browser to http://localhost:3000. You'll see Hello World!'.

Understanding the Request (req)

The req object contains everything the client sent: the URL they requested, the HTTP method (GET, POST, etc.), headers, and the body. You use this information to decide what to send back.

JavaScript
const server = http.createServer((req, res) => {
    console.log('Method:', req.method);
    console.log('URL:', req.url);
    console.log('Headers:', req.headers);
    res.end('Check your console!');
});

server.listen(3000);

Understanding the Response (res)

The res object is how you send data back to the client. You can set the status code (200 for success, 404 for not found), set headers (like Content-Type), and send the body. The res.end() method signals that the response is complete.

JavaScript
const server = http.createServer((req, res) => {
    if (req.url === '/') {
        res.statusCode = 200;
        res.setHeader('Content-Type', 'text/html');
        res.end('<h1>Home Page</h1>');
    } else {
        res.statusCode = 404;
        res.end('Page not found');
    }
});

server.listen(3000);

HTTP Methods: GET vs POST

GET is used to retrieve data. It should never change anything on the server. POST is used to send data to the server, like submitting a form or creating a new user. POST requests usually have a body containing the data being sent.

JavaScript
const server = http.createServer((req, res) => {
    if (req.method === 'GET') {
        res.end('You are GETting data');
    } else if (req.method === 'POST') {
        res.end('You are POSTing data');
    }
});

server.listen(3000);

Reading the POST Body

The request body arrives in chunks because it could be large (like a file upload). You must listen for data events to collect all the chunks, then combine them at the end. This is called streaming.

JavaScript
const server = http.createServer(async (req, res) => {
    if (req.method === 'POST') {
        let body = '';
        for await (const chunk of req) {
            body += chunk;
        }
        console.log('Received:', body);
        res.end('Data received');
    }
});

server.listen(3000);

Knowledge Check

Ready to test your understanding of 5. HTTP Module: Creating a Server?

Back