Create a web server with Nodejs and Express

·

5 min read

Create a web server with Nodejs and Express

Introduction

Web server forms the backbone of any web application, facilitating the communication between the client(such as a browser) and the backend infrastructure.

While there are numerous technologies available to build web servers, Node.js has emerged as a popular choice due to its asynchronous, event-driven nature and extensive system.

In this blog post, we will explore two ways to build a web server with Node.js: one without any framework, and another one using the Express framework.

By the end of this blog, you'll get a solid understanding of both bare-bone Node.js server creation and Express server creation.

Let's get started!

Creating a web server with Node.js

Node.js provides an HTTP module that allows developers to create a basic web server without the need for any additional frameworks or libraries. This low-level approach grants full control over the servers' behaviour and provides insight into the underlying mechanisms of web servers.

Let's walk through the steps of creating a simple HTTP server using Node.js:

Step 1: Setting up the Project

To get started, ensure you have installed Node.js on your system.

First, create a new folder for your project and initialize a pacakage.json file using the following command:

npm init -y

Step 2: Importing the http Module

In your project folder, create a new file (e.g., server.js), and import the http module to use its functionality:

//server.js
const http = require('http');

Step 3: Creating the HTTP Server

Then use http.createServer() method to create a server. This method takes a callback function as an argument. Within this callback function, we will handle the incoming HTTP requests.

//server.js
const server = http.createServer((req, res) => {
  // Here we will write logic to handle incoming HTTP requests
});

Step 4: Handling Requests

Inside the callback function, we can handle different routes and send appropriate responses to clients.

For example, let's create a simple server, that responds with "Hello, World!" for any request.

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

In this example, we have set the status code to 200 and specify the content type as plain text.

Step 5: Starting the Server

Finally, specify the port number, where the server listens to the incoming request.

const port = 3000; // You can use any available port number

server.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});

To start the server, Type a command: node server.js in the terminal. Before running the command, make sure you are in the same directory as the server.js file.

node server.js

Step 6: Defining Different Routes with Node.js

In a real-world app, we need to handle different types of routes. In the callback function, the req parameter has a req.url property that represents the requested URL name.

Example:

const server = http.createServer((req, res) => {
  if (req.url === '/') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Hello, this is the home page!');
  } else if (req.url === '/about') {
    res.writeHead(200, { 'Content-Type': 'text/plain' });
    res.end('Welcome to the About page!');
  }else {
    res.writeHead(404, { 'Content-Type': 'text/plain' });
    res.end('Page not found');
  }
});

In the example, we are checking the HTTP request by the req.url and according to that, we are returning a response.

Creating a Web Server with Express.js

Express.js is a widely used web framework built on Node.js. It provides a higher level of abstraction over Node's http module.

While building web servers from scratch with Node.js provides complete control over the server's behaviour, it can become cumbersome as your application grows in size and complexity. This is where Express.js come to the rescue. It simplifies the process of creating web servers.

Let's walk through the steps to create a web server with Express.js:

Step 1: Installing Express.js

Create a folder, move to the folder and run the following commands in the terminal:

npm init -y   /*generate package.json file */
npm install express   /* install express framework*/

Step 2: Importing and Initializing Express

In your project folder, first, create a file(e.g., server.js), you can give it any name. Then, in that file import express and create an instance of it.

//server.js
const express = require('express');
const app = express();

Step 3: Defining Routes with Express

Express.js simplify the process of creating and handling routes.

Let's create routes for the home, about, and contact pages, as we did with the Node.js server.

//server.js
const express = require('express');
const app = express();

// Route for the home page
app.get('/', (req, res) => {
  res.send('Hello, this is the home page!');
});

// Route for the about page
app.get('/about', (req, res) => {
  res.send('Welcome to the About page!');
});

// 404 route handler
app.use("*", (req, res) => {
  res.status(404).send('Page not found.');
});

With Express.js, defining routes becomes straightforward. We use app.get() to handle Get requests for specific routes and res.sent() to send responses back to clients.

Step 4: Starting the Server with Express

Similar to the Node.js approach, specify the port number where the server will listen.

//server.js
const port = 3000; // You can use any available port number

app.listen(port, () => {
  console.log(`Server is running on port: ${port}`);
});

To start the server, type node server.js in the terminal. And the server will start listening to requests on port number 3000.

node server.js

By utilizing Express.js, we can create a web server with well-defined routes quickly and our code looks more elegant.

Conclusion

We explored two approaches to creating a web server in Node.js: with only Node.js and using the Express.js framework. Both methods allow developers to build web servers that can handle HTTP requests and responses, but they differ in terms of complexity, flexibility and ease of development.

Developing web servers only with Node.js allows developers to have full control over the server's behaviour, but when the application complexity grows, managing routes becomes challenging. Our code looks verbose and it becomes difficult to manage the code.

On the other hand, Express.js allows developers to create a web server quickly and efficiently. It provides a perfect balance of power and simplicity, enabling faster development and better code organization.

References

node.org