Basic HTTP Server Examples in Node.js

Explore practical examples of creating a basic HTTP server in Node.js to enhance your programming skills.
By Taylor

Introduction

Creating a basic HTTP server in Node.js is a fundamental skill for any web developer. Node.js provides a powerful and efficient way to handle server requests and responses, making it a popular choice for building web applications. In this article, we’ll walk through three diverse examples that illustrate how to create an HTTP server in Node.js, each tailored for different use cases. Let’s get started!

Example 1: Simple HTTP Server

Context

This example demonstrates how to create a simple HTTP server that responds with a plain text message. It’s perfect for beginners who want to grasp the basics of HTTP servers in Node.js.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

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

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Notes

  • This server listens on localhost at port 3000. You can test it by navigating to http://127.0.0.1:3000 in your web browser.
  • Feel free to replace the message in res.end with any text you like!

Example 2: JSON Response Server

Context

In this example, we will create an HTTP server that sends back a JSON response. This is useful for APIs where you need to return structured data to the client.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'application/json');
    const responseData = { message: 'Hello, JSON!', date: new Date() };
    res.end(JSON.stringify(responseData));
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Notes

  • When you access http://127.0.0.1:3000, you will receive a JSON object. This is particularly handy for developers building RESTful APIs.
  • You can modify the responseData object to include any data relevant to your application.

Example 3: Server with Routing

Context

This example showcases how to implement basic routing in your HTTP server. This allows the server to respond differently based on the request URL, making it more versatile.

const http = require('http');

const hostname = '127.0.0.1';
const port = 3000;

const server = http.createServer((req, res) => {
    res.statusCode = 200;
    res.setHeader('Content-Type', 'text/plain');

    if (req.url === '/') {
        res.end('Welcome to the Home Page!\n');
    } else if (req.url === '/about') {
        res.end('This is the About Page!\n');
    } else {
        res.statusCode = 404;
        res.end('404 Not Found\n');
    }
});

server.listen(port, hostname, () => {
    console.log(`Server running at http://${hostname}:${port}/`);
});

Notes

  • This server responds with different messages for the routes / and /about, and returns a 404 error for any other routes.
  • You can expand this routing functionality by adding more conditions based on the URL and even handling different HTTP methods like POST or DELETE.

Conclusion

These examples of creating a basic HTTP server in Node.js illustrate the versatility and ease of use of Node.js for web development. Whether you’re building a simple application, an API, or a more complex server, these foundational skills will serve you well in your programming journey.