How to Create a Simple Web Server Using Node.js and Express

Overview

Node.js is the N and Express.js is the E in the MEAN Stack, one of the most popular Web Stacks for VPS hosting.

Express.js is the most popular Node.js web application framework. Express abstracts away quite a bit of the coding necessary for the backend of an application, making it much easier and more efficient to develop applications. That is, you don’t have to reinvent the wheel.

Special Note: some leading VPS hosting services provide easy 1-click installations of software like node.js or Express.js. Look for these 1-click installs in the plan you purchase to save valuable time.

Section 1 - Install Express.js and prepare a project

Step 1 - Update your package index

If you use Ubuntu, update your package index, so you get newer versions of packages you install.

$ sudo apt-get update

If you use CentOS, then update and upgrade your packages.

$ sudo yum check-update
$ sudo yum upgrade
$ yum clean all

Step 2 - Create a directory for your project

If you haven’t yet installed Node.js, see <Install Node.js on your Linux VPS.>

First, create a directory for this application.

$ mkdir serverapp

Then, change directories into the directory you created.

$ cd serverapp

Step 3 - Run NPM init

In the server app directory, run the npm init utility. Accept the defaults, entering “Simple Web Server” when prompted for a project description.

$ npm init

Hit return to accept the defaults for these questions.

This utility will walk you through creating a package.json file.
It only covers the most common items and tries to guess sensible defaults.

See `npm help json` for definitive documentation on these fields and exactly what they do.

Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.

Press ^C at any time to quit.
package name: (serverapp) 
version: (1.0.0) 
description: 
git repository: 
keywords: 
author: 
license: (ISC) 
About to write to /home/marmot/serverapp/package.json:

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

Is this ok? (yes) yes

Step 4 - Install Express.js

Install Express in the serverapp directory.

$ npm install express --save

Now you’re ready to get started with your web server application.

Step 5- Allow port 3000 through Your VPS’s firewall

If you’re using Ubuntu for your virtual server, allow port 3000 through the Uncomplicated Firewall (UFW).

$ sudo ufw allow 3000

If you’re using CentOS for your virtual server, allow port 3000 through firewalld.

$ sudo firewall-cmd --zone=public --add-port=3000/tcp

Section 2 - Write your Express “Hello World” script

Step 1 - Initialize Express

You’ll need to create two variables to use Express. Here you can use var for variable or, per the newer version of JavaScript (ES6), use const (constant) to initialize variables that are really constants. That is, with ES6 it’s better to use const for variables that aren’t going to change.

const express = require('express' 4.16.3);
const app = express()

Then, use get to issue the http get command. Create a call back function to respond to requests made to the URL and port, responding with “Hello World!” To any get requests.

app.get('/', (request, response) {
    response.send('Hello World!));
});

Then, create the listening function listening for "get" requests to port 3000.

app.listen(3000, console.log('App Listening to port 3000');

Here’s your complete Express “Hello World” application.

const express = require('express' 4.16.3);
const app = express();

app.get('/', (request, response) {
    response.send('Hello World!));
});

app.listen(3000, console.log('App Listening to port 3000');

Section 3 - Serve static content

You’ll start to see the power of Node and Express with this section, calling a standard HTML document familiar to those who’ve created or edited a static website for a web hosting account.

Step 1 - Create the root web directory for this project

Create a directory called www in your home directory.

Step 2 - Create an HTML file

Create an HTML file using your favorite editor, opening the file in your favorite editor, setting the doctype to html, which makes it an HTML document. Set the HTML language to whatever language you prefer, and then include the typical HTML document sections.

<!doctype html>

<head>
    <meta charset="UTF-8">

    <title>Hello World!</title>
</head>

<body>
    <h1>Hello World!</h1>
</body>

</html>

Step 3 - Set the path

Set the path to the content you want to serve. For this application, keep it simple with just a path to static content.  In this case, the path is ../www. The .. goes up one directory level and the /www takes you into the www directory.

app.use(express.static(path.join(__dirname, '../www'));

Step 4 - Create the server function

The server function listens for whatever port you’ve assigned to the port variable (3000 in this case), responding to http get requests to your virtual server’s IP address or domain name (if you set up your domain name for your VPS hosting).

This function returns a console log telling you the server app’s running, listening to port 3000.

app.listen(3000, function() {
    console.log('Web app listening on port 3000');
});

Here’s the entire script.

const express = require('express');
const app = express();

app.get('/', function (request, response) {
        response.send('Hello World');
});

app.listen(3000, function () {
        console.log('Listening on port 3000');
});

Section 4 - Add some routes to your application

Routing refers to the different paths to the various responses your application can have to http requests such as get, put, and delete.

Step 1 - Add a “home” route

The root route responds to requests to the root of the server. For a website, you might call this your “Home” route.

app.get('/', function (req, res) {
  res.send('Home')
})

Step 2 - Add an “about” route

You can add a route for any path after the root. Add an about route that returns a simple “About Us” when a visitor goes to http://YOUR_VPS_IP_ADDRESS:3000/about.

app.get('/about', function (req, res) {
  res.send('About Us')
})

Here's your script with both routes added.

const express = require('express');
const app = express();

app.get('/', function (request, response) {
        response.send('Home');
});

app.get('/about', function (request, response) {
        response.send('About Us');
});

app.listen(3000, function () {
        console.log('Listening on port 3000');
});

There’s a lot more you can do with routes, but this gives you a glimpse of how you’d create routes for a website or web application hosted on your virtual server.

Conclusion

You’ve created a simple web server using Node.js and Express.js, learning to serve static HTML content, and gaining a basic understanding of how routing works.

You can build on what you’ve learned by starting a website or web application project using Node and Express, building on what you’ve created.

 

Check out these top 3 Node.js hosting services:

Was this article helpful?