Basic Express Server with Node.js

Basic Express Server with Node.js

Express is a web application framework for Node.js that allows you to create APIs and web servers in a much easier and cleaner way. It is a lightweight package that does not obscure the core Node.js features.

Create a Project

First, create a directory and then open it in the terminal

$ mkdir express-basic-server
$ cd express-basic-server

After that let’s initialize the node project by running the command npm init and answer a few questions

$ npm init

that’s going to create a new file called package.json with content very similar to

{
  "name": "express-basic-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC"
}

Installation

Now we will need to install express, that’s very easy, install it via npm (node package manager) as you would with any other package

npm install express --save

that’s going to update the file package.json with the express dependency and install it in the node_moudles folder

{
  "name": "express-basic-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.0"
  }
}

Create a Server

Create an HTTP server is very easy in Express. First, we need to create a file where we will set up our server, the most common names are app.js and server.js but you can call as you want

$ touch server.js

The first line is to import express that we already installed, this will give us the main Express module from the package you installed, which is a function.

const express = require('express');

We then run this function to create our app variable.

const app = express();

Note: You can create multiple apps this way, each with their requests and responses.

Now let’s define the port that the server will be listening, it’s a great idea to take that from the environment variables, so could be easily configurated and by default we will set it as 3000

const port = process.env.port || 3000;

At last, we must start our server! We are passing the port into the listen function. The function passed-in as the second optional parameter, and runs when the server starts up. This just gives us some feedback on the console to know that our application is running.

app.listen(port, () => {
    console.log(`Server listening on port ${port}!`);
});

Now we have a basic server

const express = require('express');

const app = express();

const port = process.env.port || 3000;

app.listen(port, () => {
    console.log(`Server listening on port ${port}!`);
});

To run the server let use the next command

$ node server.js

or

$ nodemon server.js

Note: If you would like to use nodemon you have to install it

The major difference between the node and the nodemon commands are that if you use node command you manually run the command each time after save but if you use nodemon command it detects the changes automatically in any file of the project.

You can install nodemon globally by running the command

$ npm install nodemon -g

Or you can install it as a dev dependency in the project and set a script to run the server with nodemon

$ npm install nodemon --save-dev

Now we have the package.json file like

{
  "name": "express-basic-server",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "server": "nodemon server.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "express": "^4.17.0"
  },
  "devDependencies": {
    "nodemon": "^1.19.0"
  }
}

And we can run the server by running the command

$ npm run server

Basic Routing

The main responsibility of any server is how the application responds to the client request to specific endpoints like path by specific HTTP methods. In the server-side routing, each route has one route method, one route path, and one or more route handler functions.

Let’s listen in our server to the path / by the HTTP method get and responds an <h1> HTML tag with Hello World!

app.get('/', (req, res) => {
  res.send('<h1>Hello World!</h1>')
});

Now our server.js file like looks like

const express = require('express');

const app = express();

const port = process.env.port || 3000;

app.get('/', (req, res) => {
  res.send('<h1>Hello World!</h1>')
});

app.listen(port, () => {
    console.log(`Server listening on port ${port}!`);
});

There we have it, a basic Express server using Node.js. Now after running the server you can access to the http://localhost:3000 and see the results


Middleware

With Express, we can write and use middleware functions, which have access to all HTTP requests coming to the server. These functions can:

  • Make changes to the request and the response objects.
  • End the request-response cycle.
  • Call the next middleware function in the stack
  • Execute any block of code.

We can write our own middleware functions, or use third-party middleware by importing them the same way we would with any other package.

Let’s start by writing our own middleware. To define a middleware function, we call app.use() and pass it a function. This function will be an Application-level Middleware , the parameters passed to the method are req, res and next, these are the incoming request, the response being written and a method to tells the middleware to go to the next middleware function in the chain once the current middleware is finished, if there is one

Note: Is important to include at the end of our function - otherwise, the request will get stuck on this middleware.

Let’s create a basic middleware function to print the current time in the console during every request:

app.use((req, res, next) => {
    console.log('Time: ', Date.now());
    next();
});

We can optionally pass a path to the middleware, which will only handle requests to that route, as we do in the Basic Routing. For example:

app.use('/test', (req, res, next) => {
    console.log('Request type: ', req.method);
    next();
});

By passing /test as the first argument to app.use(), this function will only run for requests sent to http://localhost:3000/test.

Now let’s try using some existing middleware to serve static files. Note that Express comes with a built-in middleware function express.static(). First, inside the same folder where the express server is located, create a folder called public and put some files in there (any files will do, perhaps some images).

$ mkdir public
$ cd public
$ wget https://lorempixel.com/400/200/city/

Now, let’s include the express.static middleware and tell the path to access from and the name of our folder:

app.use('/public', express.static('public'));

Now when you restart your server and navigate to http://localhost:3000/public. You should see all your files!

There we have it, a Basic Express server with Node.js. To learn more about Express, you can take a look on their website, they have multiple guides and documentation express