SyntaxStudy
Sign Up
Node.js Creating an HTTP Server
Node.js Beginner 10 min read

Creating an HTTP Server

Node's built-in http module lets you build a web server without any external dependencies. The createServer() function takes a callback with the req (request) and res (response) objects.

You can inspect req.url and req.method to implement basic routing.

Example
const http = require('http');

const server = http.createServer((req, res) => {
    const { method, url } = req;

    // Simple router:
    if (url === '/' && method === 'GET') {
        res.writeHead(200, { 'Content-Type': 'text/html' });
        res.end('<h1>Home Page</h1>');

    } else if (url === '/api/users' && method === 'GET') {
        const users = [
            { id: 1, name: 'Alice' },
            { id: 2, name: 'Bob' },
        ];
        res.writeHead(200, { 'Content-Type': 'application/json' });
        res.end(JSON.stringify(users));

    } else if (url === '/api/users' && method === 'POST') {
        let body = '';
        req.on('data', chunk => { body += chunk; });
        req.on('end', () => {
            const newUser = JSON.parse(body);
            console.log('New user:', newUser);
            res.writeHead(201, { 'Content-Type': 'application/json' });
            res.end(JSON.stringify({ message: 'Created', user: newUser }));
        });

    } else {
        res.writeHead(404, { 'Content-Type': 'text/plain' });
        res.end('404 Not Found');
    }
});

server.listen(3000, () => console.log('Server on port 3000'));