Topics HTTP & Networking Creating HTTP Servers
beginner 16 min read

Creating HTTP Servers

Build HTTP servers from scratch using the built-in http module.

HTTP Server

const http = require('http');\n\nconst server = http.createServer((req, res) => {\n  // req is IncomingMessage (Readable stream)\n  // res is ServerResponse (Writable stream)\n  \n  res.writeHead(200, { 'Content-Type': 'application/json' });\n  res.end(JSON.stringify({\n    message: 'Hello from Node.js',\n    method: req.method,\n    url: req.url,\n  }));\n});\n\nserver.listen(3000, () => {\n  console.log('Server listening on port 3000');\n});

Routing

const server = http.createServer((req, res) => {\n  const { method, url } = req;\n  \n  if (url === '/' && method === 'GET') {\n    res.end('Home page');\n  } else if (url === '/api/users' && method === 'GET') {\n    res.end(JSON.stringify([{ id: 1, name: 'Alice' }]));\n  } else if (url.match(/^\/api\/users\/(\d+)$/) && method === 'GET') {\n    const id = url.match(/^\/api\/users\/(\d+)$/)[1];\n    res.end(JSON.stringify({ id: Number(id), name: 'Alice' }));\n  } else {\n    res.writeHead(404);\n    res.end('Not found');\n  }\n});

Request Body

let body = '';\nreq.on('data', chunk => body += chunk);\nreq.on('end', () => {\n  const data = JSON.parse(body);\n  console.log('Received:', data);\n});

Examples

const http = require('http');

const server = http.createServer((req, res) => {
  // Parse URL
  const url = new URL(req.url, `http://${req.headers.host}`);
  
  res.writeHead(200, { 'Content-Type': 'text/html' });
  
  if (url.pathname === '/') {
    res.end('<h1>Home</h1><a href="/about">About</a>');
  } else if (url.pathname === '/about') {
    res.end('<h1>About Node.js</h1><p>Node.js is a JavaScript runtime.</p>');
  } else {
    res.writeHead(404);
    res.end('<h1>404 - Not Found</h1>');
  }
});

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

Your Notes

Sign in to take notes for this lesson.

Discussion

Sign in to join the discussion.

Flashcards

Sign in to create flashcards.