Building a Simple Web Server

How to build a basic web server simply

Building a Simple Web Server

Welcome to Day 6 of our Node.js blog series!

Today, we’ll delve into building a simple web server using Node.js. We’ll cover the basics of creating an HTTP server, handling different types of requests, serving static files, and introducing routing. By the end of this post, you'll have a solid understanding of how to build and run a basic web server with Node.js.

What is a Web Server?

A web server is software that handles HTTP requests from clients (usually web browsers) and serves back HTTP responses, typically including web pages or other resources. Node.js provides a built-in http module, which allows you to create a web server easily.

Creating a Basic HTTP Server

  1. Importing the http Module:

    • To create a web server in Node.js, you first need to import the http module.

    • Example:

        const http = require('http');
      
  2. Creating the Server:

    • Use the http.createServer method to create a new HTTP server. This method takes a callback function that is executed whenever a request is received.

    • Example:

        const server = http.createServer((req, res) => {
          res.statusCode = 200; // HTTP status code
          res.setHeader('Content-Type', 'text/plain'); // Response header
          res.end('Hello, World!\n'); // Response body
        });
      
  3. Starting the Server:

    • Use the server.listen method to start the server and make it listen for incoming requests on a specified port and hostname.

    • Example:

        const port = 3000;
        const hostname = '127.0.0.1';
      
        server.listen(port, hostname, () => {
          console.log(`Server running at http://${hostname}:${port}/`);
        });
      
  4. Complete Example:

     const http = require('http');
    
     const server = http.createServer((req, res) => {
       res.statusCode = 200;
       res.setHeader('Content-Type', 'text/plain');
       res.end('Hello, World!\n');
     });
    
     const port = 3000;
     const hostname = '127.0.0.1';
    
     server.listen(port, hostname, () => {
       console.log(`Server running at http://${hostname}:${port}/`);
     });
    

Handling Different Types of Requests

  1. Examining the Request Object:

    • The req object contains information about the incoming request, such as the URL, method, and headers.

    • Example:

        const server = http.createServer((req, res) => {
          console.log(`Request URL: ${req.url}`);
          console.log(`Request Method: ${req.method}`);
      
          res.statusCode = 200;
          res.setHeader('Content-Type', 'text/plain');
          res.end('Hello, World!\n');
        });
      
  2. Handling GET Requests:

    • Example:

        const server = http.createServer((req, res) => {
          if (req.method === 'GET' && req.url === '/') {
            res.statusCode = 200;
            res.setHeader('Content-Type', 'text/html');
            res.end('<h1>Welcome to the Home Page</h1>');
          } else {
            res.statusCode = 404;
            res.setHeader('Content-Type', 'text/plain');
            res.end('404 Not Found');
          }
        });
      
  3. Handling POST Requests:

    • Example:

        const server = http.createServer((req, res) => {
          if (req.method === 'POST' && req.url === '/submit') {
            let body = '';
            req.on('data', chunk => {
              body += chunk.toString();
            });
            req.on('end', () => {
              console.log(`Received data: ${body}`);
              res.statusCode = 200;
              res.setHeader('Content-Type', 'text/plain');
              res.end('Data received');
            });
          } else {
            res.statusCode = 404;
            res.setHeader('Content-Type', 'text/plain');
            res.end('404 Not Found');
          }
        });
      

Serving Static Files

To serve static files such as HTML, CSS, and JavaScript files, you can use the fs module to read files from the file system and send them in the response.

  1. Serving an HTML File:

    • Example:

        const fs = require('fs');
      
        const server = http.createServer((req, res) => {
          if (req.method === 'GET' && req.url === '/') {
            fs.readFile('index.html', (err, data) => {
              if (err) {
                res.statusCode = 500;
                res.setHeader('Content-Type', 'text/plain');
                res.end('500 Internal Server Error');
              } else {
                res.statusCode = 200;
                res.setHeader('Content-Type', 'text/html');
                res.end(data);
              }
            });
          } else {
            res.statusCode = 404;
            res.setHeader('Content-Type', 'text/plain');
            res.end('404 Not Found');
          }
        });
      

Introducing Routing

Routing allows you to define different endpoints and handle different types of requests more cleanly. You can implement basic routing manually, or use a framework like Express for more advanced routing.

  1. Manual Routing:

    • Example:

        const server = http.createServer((req, res) => {
          if (req.method === 'GET') {
            if (req.url === '/') {
              res.statusCode = 200;
              res.setHeader('Content-Type', 'text/html');
              res.end('<h1>Home Page</h1>');
            } else if (req.url === '/about') {
              res.statusCode = 200;
              res.setHeader('Content-Type', 'text/html');
              res.end('<h1>About Page</h1>');
            } else {
              res.statusCode = 404;
              res.setHeader('Content-Type', 'text/html');
              res.end('<h1>404 Not Found</h1>');
            }
          } else {
            res.statusCode = 405;
            res.setHeader('Content-Type', 'text/html');
            res.end('<h1>405 Method Not Allowed</h1>');
          }
        });
      
  2. Using Express for Routing:

    • Install Express:

        npm install express
      
    • Example:

        const express = require('express');
        const app = express();
      
        app.get('/', (req, res) => {
          res.send('<h1>Home Page</h1>');
        });
      
        app.get('/about', (req, res) => {
          res.send('<h1>About Page</h1>');
        });
      
        const port = 3000;
        app.listen(port, () => {
          console.log(`Server running at http://localhost:${port}/`);
        });
      

Conclusion

Today, we've covered the basics of building a simple web server with Node.js. We started by creating a basic HTTP server, then moved on to handling different types of requests, serving static files, and introducing basic routing. Understanding these concepts is essential for building more complex web applications.

In the next post, we'll delve deeper into Understanding Asynchronous Programming. Stay tuned for more in-depth Node.js content!