#1 Data Analytics Program in India
₹2,499₹1,499Enroll Now
4 min read
Question 30 of 62medium

How to create an HTTP server in Node.js?

Building HTTP servers with the built-in http module.

What You'll Learn

  • Creating HTTP server
  • Handling requests
  • Sending responses

Basic HTTP Server

code.jsJavaScript
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 on port 3000');
});

Request Object

code.jsJavaScript
http.createServer((req, res) => {
  console.log(req.method);      // GET, POST, etc.
  console.log(req.url);         // /path?query=value
  console.log(req.headers);     // request headers

  // Parse URL
  const url = new URL(req.url, `http://${req.headers.host}`);
  console.log(url.pathname);    // /path
  console.log(url.searchParams.get('query')); // value
});

Routing

code.jsJavaScript
http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/html' });
    res.end('<h1>Home</h1>');
  } else if (req.method === 'GET' && req.url === '/api/users') {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.end(JSON.stringify([{ id: 1, name: 'John' }]));
  } else {
    res.writeHead(404);
    res.end('Not Found');
  }
}).listen(3000);

Reading Request Body

code.jsJavaScript
http.createServer((req, res) => {
  let body = '';
  req.on('data', chunk => body += chunk);
  req.on('end', () => {
    const data = JSON.parse(body);
    res.end('Received: ' + data.name);
  });
}).listen(3000);