Node.js HTTP Server with Examples for Beginners

node js http server

This article shows how Node.js creates HTTP servers. It covers requests, responses, routes, HTML, JSON, and gives examples for both intermediate and advanced use cases.

What is Node.js HTTP Server?

A Node.js HTTP server is a process that listens on a port and answers client requests. It allows developers to send data, serve files, or return responses to browsers.

Node.js uses the built-in http module to create servers. This module runs without extra setup and handles each request with an event-driven model.

Node.js uses the built-in http module to create servers. This module runs without extra setup and handles each request with an event-driven model.

const http = require('http');

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

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

This code imports the http module, creates a server, and sets it to listen on port 3000. The server returns a plain-text message for any request.

A Node.js server reads each request and decides what response to send. It can read headers, method, and URL to send the right content.

How to Add Routes in an HTTP Server

You can check the request URL to decide what content to return. This allows you to build multiple paths inside the same server.

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('Home Page');
  } else if (req.url === '/about') {
    res.writeHead(200, {'Content-Type': 'text/plain'});
    res.end('About Page');
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Page Not Found');
  }
});

server.listen(3000);

This code checks the URL and sends a different response for each path.

Serving HTML and JSON with Node.js HTTP Server

You can serve HTML files or JSON data. HTML helps show pages in browsers, and JSON helps return data for APIs.

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/html') {
    res.writeHead(200, {'Content-Type': 'text/html'});
    res.end('<h1>Welcome to HTML page</h1>');
  } else if (req.url === '/json') {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify({ message: 'Hello JSON' }));
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Page Not Found');
  }
});

server.listen(3000);

This code shows how to serve HTML content and JSON data from one server.

Examples

Basic Text Response:

const http = require('http');

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

server.listen(4000);

This example creates a server on port 4000 that returns a plain-text response for all requests. It is simple and helps beginners learn the basics.

Multiple Routes with JSON Data:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.url === '/users') {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify([{name: 'Ali'}, {name: 'Sara'}]));
  } else if (req.url === '/status') {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify({status: 'Server OK'}));
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not Found');
  }
});

server.listen(4001);

This example shows a server with two JSON routes and a 404 fallback. It helps you handle structured data with different paths.

Serve HTML File from Disk:

const http = require('http');
const fs = require('fs');

const server = http.createServer((req, res) => {
  if (req.url === '/page') {
    fs.readFile('index.html', (err, data) => {
      if (err) {
        res.writeHead(500, {'Content-Type': 'text/plain'});
        res.end('Error loading file');
      } else {
        res.writeHead(200, {'Content-Type': 'text/html'});
        res.end(data);
      }
    });
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Page Not Found');
  }
});

server.listen(4002);

This example shows how to serve an HTML file from the disk. It reads the file and returns its content when the client visits /page.

Advanced Routing with Methods:

const http = require('http');

const server = http.createServer((req, res) => {
  if (req.method === 'GET' && req.url === '/data') {
    res.writeHead(200, {'Content-Type': 'application/json'});
    res.end(JSON.stringify({message: 'GET data'}));
  } else if (req.method === 'POST' && req.url === '/data') {
    let body = '';
    req.on('data', chunk => body += chunk);
    req.on('end', () => {
      res.writeHead(200, {'Content-Type': 'application/json'});
      res.end(JSON.stringify({received: body}));
    });
  } else {
    res.writeHead(404, {'Content-Type': 'text/plain'});
    res.end('Not Found');
  }
});

server.listen(4003);

This example shows a server that handles GET and POST requests on the same route. It collects posted data and returns it as JSON.

Wrapping Up

You learned what a Node.js HTTP server is and how it handles requests, responses, routes, and different data types. Here is a quick recap:

  • Node.js can create an HTTP server with the built-in module.
  • It can handle different URLs and return text, HTML, or JSON.
  • It can read data from files and send it to clients.
  • It can handle GET and POST methods for advanced cases.

FAQs

How do I create a simple Node.js HTTP server?


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/");
});
Explanation: Use http.createServer to create a server and listen to start it on a port.

How to handle different routes in Node.js HTTP server?


const http = require("http");

const server = http.createServer((req, res) => {
  if (req.url === "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>Home Page</h1>");
  } else if (req.url === "/about") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>About Page</h1>");
  } else {
    res.writeHead(404, { "Content-Type": "text/plain" });
    res.end("404 Not Found");
  }
});

server.listen(3000);
Explanation: You can use req.url to check the path and serve different responses.

How can I send JSON response with Node.js HTTP server?


const http = require("http");

const server = http.createServer((req, res) => {
  if (req.url === "/api") {
    const data = { name: "John", age: 30 };
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(data));
  }
});

server.listen(3000);
Explanation: Set header Content-Type to application/json and use JSON.stringify().

How to serve HTML files using Node.js HTTP server?


const http = require("http");
const fs = require("fs");

const server = http.createServer((req, res) => {
  fs.readFile("index.html", (err, data) => {
    if (err) {
      res.writeHead(500);
      res.end("Error loading file");
    } else {
      res.writeHead(200, { "Content-Type": "text/html" });
      res.end(data);
    }
  });
});

server.listen(3000);
Explanation: Use fs.readFile to load HTML files and return them in the response.

Similar Reads

Node Version Manager (NVM): Manage Node.js Versions

NVM (Node Version Manager ) is a command-line tool used to manage multiple versions of Node.js on a single machine.…

Node.js File System with Examples

Node.js file system lets you read, write, update, and manage files and folders with built-in methods. Understand the Node.js File…

Node.js Hello World: Write Your First Program

In this quick tutorial, you will start Node.js tutorials with a Hello World program. You will learn how to set…

Installing Node js on Windows, Ubuntu, and MacOS

Installing node js on Windows, Ubuntu, or macOS. You need to pick the version of Node.js that you want to…

What is NodeJS? An Introduction to Node.js

What is Nodejs? Node.js is a powerful cross-platform JavaScript runtime that enables developers to execute JavaScript code on the server-side.…

Node.js Modules in Depth with Examples

This guide shows Node.js modules, how they work, how to import and export them, and why you use them. What…

Node.js Streams Guide: How to Handle Data with Examples

Streams pass data in parts, so the app stays fast. This article explains Node.js Streams and how to use them.…

Node js NPM: How to Publish and Install JS Packages

Node Package Manager (NPM) is an essential tool at the heart of the Node.js ecosystem. This is the defacto package…

Node JS Buffers Tutorial for Beginners and Pros

Node JS Buffers store raw binary data in memory. This guide shows how to create them, work with them, and…

Node JS Events in Depth with Examples

Node JS runs code in an event-based model and uses events to drive tasks. An event is a signal that…

Previous Article

How to Create HTML Nested Lists with Examples

Next Article

JavaScript toString Function: How it Works with Examples

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *


Subscribe to Get Updates

Get the latest updates on Coding, Database, and Algorithms straight to your inbox.
No spam. Unsubscribe anytime.