All aboard the Express.js

Dylan Crawshaw
11 min readFeb 5, 2021

Express is a lightweight and customizable Node.js framework that gives you a plethora of features for web and mobile apps. With a robust number of HTTP utility functions and middleware, it is super easy to create a powerful API.

To add it to your Node project all you must do is

$ npm install express --save

Or if you don’t want to add it to your dependencies and just use it temporarily

$ npm install express --no-save

Now I will show you how to create a simple crud app using Express and MongoDB

First, create a folder for the app and run npm init.

Next, create a file for your server. I am going to just call my server.js.

touch server.js

Next, we are going to add nodemon, this will help us in development by automatically restarting the application when file changes in the directory are detected. We will also need to install express. Make sure you have a .gitignore file in your root directory with node_modules in it.

npm install --save-dev nodemon

Next, we use express in server.js by requiring it.

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

We need to create a server that browsers can connect to. We do this by using Express’s listen method.

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

Now, run node server.js and navigate to localhost:3000 on your browser. You should see a message that says cannot get /.

Getting started

Start by creating a folder for this project. Feel free to call it anything you want. After you’ve created the folder, navigate into it with the Terminal and run npm init.

npm init creates a package.json file which helps you manage dependencies (which we will install as we go through the tutorial).

$ npm init

Just hit enter through everything that appears. I’ll talk about the ones you need to know as we go along.

Running Node for the first time in your life

The simplest way to use node is to run the node command, and specify a path to a file. Let’s create a file called server.js to run node with.

touch server.js

Next, put this a console.log statement into server.js. This lets us know whether Node is running properly.

// server.js
console.log('May Node be with you')

Now, run node server.js in your command line and you should see this:

Great. Node works. The next step is to learn to use Express.

Using Express

First, we have to install Express. We can do this by running the npm install command. (npm is installed with Node, which is why you use commands like npm init and npm install).

Run npm install express --save command in your command line.

The --save flag saves express as a dependency in package.json. It’s important to know these dependencies because npm can retrieve dependencies with another npm install command when you need it later.

npm install express --save

Next, we use express in server.js by requiring it.

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

We need to create a server that browsers can connect to. We do this by using the Express’s listen method.

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

Now, run node server.js and navigate to localhost:3000 on your browser. You should see a message that says cannot get /.

That’s a good sign. It means we can now communicate to our express server through the browser. This is where we begin CRUD operations.

CRUD — READ

Browsers perform the READ operation when you visit a website. Under the hood, they send a GET request to the server to perform this READ operation.

You see cannot get / because our server sent nothing back to the browser.

In Express, we handle a GET request with the get method:

app.get(endpoint, callback)

endpoint is the requested endpoint. It’s the value that comes after your domain name. Here are some examples:

  • When you visit localhost:3000, you’re actually visiting localhost:3000/. In this case, browsers requested for /.
  • You’re reading this article on https://zellwk.com/blog/crud-express-mongodb/. The domain name is zellwk.com. The requested endpoint is anything that comes after zellwk.com (which is /blog/crud-express-mongodb).

callback tells the server what to do when the requested endpoint matches the endpoint stated. It takes two arguments: A request object and a response object.

// We normally abbreviate `request` to `req` and `response` to `res`.
app.get('/', function (req, res) {
// do something here
})

For now, let’s write Hello World back to the browser. We do so by using a send method that comes with the response object:

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

I’m going to start writing in ES6 code and show you how to convert to ES6 along the way as well. First off, I’m replacing function() with an ES6 arrow function. The below code is the same as the above code:

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

Now, restart your server by doing the following:

  1. Stop the current server by hitting CTRL + C in the command line.
  2. Run node server.js again.

Then, navigate to localhost:3000 on your browser. You should be able to see a string that says “Hello World”.

Great.

Next, let’s change server.js so we serve up an index.html page back to the browser. To do this, we use the sendFile method that’s provided by the res object.

app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html')
// Note: __dirname is the current directory you're in. Try logging it and see what you get!
// Mine was '/Users/zellwk/Projects/demo-repos/crud-express-mongo' for this app.
})

In the sendFile method above, we told Express to serve an index.html file that can be found in the root of your project folder. We don’t have that file yet. Let’s make it now.

touch index.html

Let’s put some text in our index.html file as well:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>MY APP</title>
</head>
<body>
<h1> May Node and Express be with you. </h1>
</body>
</html>

Restart your server and refresh your browser. You should be able to see your HTML file now.

This is how Express handles a GET request (READ operation) in a nutshell.

At this point, you probably have realized that you need to restart your server whenever you make a change to server.js. This is process is incredibly tedious, so let’s take a quick detour and streamline it by using a tool called nodemon.

Enter Nodemon

Nodemon restarts the server automatically when you save a file that’s used by the server.js. We can install Nodemon with the following command:

$ npm install nodemon --save-dev

We use a --save-dev flag here because we only use Nodemon when we are developing stuff. We won’t use Nodemon on an actual server. --save-dev here adds Nodeman as a devDependency in the package.json file.

Nodemod behaves like Node. So you can run nodemon server.js and you’d expect to see the same thing. Unfortunately, this only works if you’ve installed nodemon globally with the -g flag (and we didn’t do this).

We have other ways to run Nodemon. For example, you can execute Nodemon directly from the node_modules folder. This is super unweildy, but it works:

./node_modules/.bin/nodemon server.js

We can make things simpler by adding script key in the package.json file. This lets us run nodemon server.js without the ./node_modules... preamble.

{
// ...
"scripts": {
"dev": "nodemon server.js"
}
// ...
}

Now, you can run npm run dev to trigger nodemon server.js.

Back to the main topic. We’re going to cover the CREATE operation next.

CRUD — CREATE

Browsers can only perform a CREATE operation if they send POST request to the server. This POST request can be triggered through JavaScript or through a <form> element.

Let’s figure out how to use a <form> element to create new entries for this Star Wars quote application for now. We’ll examine how to send requests via JavaScript later.

To send a POST request through a <form>, you need to add the <form> element to your index.html file.

You need three things on this form element:

  1. An action attribute
  2. A method attribute
  3. name attributes on each <input> elements within the form
<form action="/quotes" method="POST">
<input type="text" placeholder="name" name="name">
<input type="text" placeholder="quote" name="quote">
<button type="submit">Submit</button>
</form>

The method tells browsers what kind of request to send. In this case, we use POST because we’re sending a POST request.

The action attribute tells the browser where to send the POST request. In this case, we’re send the POST request to /quotes.

We can handle this POST request with a post method in server.js. The path path should be the value you placed in the action attribute.

app.post('/quotes', (req, res) => {
console.log('Hellooooooooooooooooo!')
})

Restart your server (hopefully you’ve set up Nodemon so it restarts automatically) and refresh your browser. Then, enter something into the <form> element and submit the form. Next, look at your command line. You should see Hellooooooooooooooooo! in your command line.

Great, we know that Express is handling the form for us right now. The next question is, how do we get the input values with Express?

Turns out, Express doesn’t handle reading data from the <form> element on it’s own. We have to add another package called body-parser to gain this functionality.

npm install body-parser --save

Body-parser is a middleware. They help to tidy up the request object before we use them. Express lets us use middleware with the use method.

const express = require('express')
const bodyParser= require('body-parser')
const app = express()
// Make sure you place body-parser before your CRUD handlers!
app.use(bodyParser.urlencoded({ extended: true }))
// All your handlers here...
app.get('/', (req, res) => {/*...*/})
app.post('/quotes', (req, res) => {/*...*/})

The urlencoded method within body-parser tells body-parser to extract data from the <form> element and add them to the body property in the request object.

You should be able to see values from the <form> element inside req.body now. Try doing a console.log and see what it is!

app.post('/quotes', (req, res) => {
console.log(req.body)
})

You should see an object similar to the following:

Hmmm.

Master Yoda has spoken! Let’s make sure we remember Yoda’s words. It’s important. We want to be able to retrieve it the next time we load our index page.

Enter the database, MongoDB.

MongoDB

MongoDB is a database. We can store information into this database to remember Yoda’s words. Then, we can retrieve this information and display to people who view our app.

I normally use Mongoose (which is a framework for MongoDB) when I use MongoDB. I’ll teach you how to use basic MongoDB in this article. If you want to learn Mongoose, consider reading my article on Mongoose.

First, we need to install MongoDB via npm.

npm install mongodb --save

Once installed, we can connect to MongoDB through the MongoClient's connect method as shown in the code below:

const MongoClient = require('mongodb').MongoClientMongoClient.connect('mongodb-connection-string', (err, client) => {
// ... do something here
})

The next part is to get the correct link to our database. Most people store their databases on cloud services like MongoDB Atlas. We’re going to do same as well. (It’s free).

You can also create a database on your computer for development work. Read “How to setup a local MongoDB Connection” for instructions.

Setting up MongoDB Atlas

Go ahead and create an account on MongoDB Atlas. Once you’re done, you need to create an “Organization”. It’s sort of like a company name. You can name it anything you want. (You can change it later).

You also need to select a cloud service. Go ahead with MongoDB Atlas in this case.

Next, you need to set permissions for users. MongoDB Atlas will automatically fill up your current email address as the user. So just continue to the next step.

You should end up with a screen that looks like this:

Next, you need to create a Database in MongoDB Atlas. There are several steps to do this.

First, you need to create a new Project. You can do this by going under “Context” in the top left hand menu. Click the Dropdown. Then, select New Project.

Next, you will need to name your project. Call it anything you want. I’m going to call this star-wars.

Then, you will need to add members. Again, you’re already added so go ahead and click “Create Project” to move on.

You should end up with a screen that says Create a Cluster.

Click on “Build a Cluster”. You should see this screen:

Select the free cluster (left option) and continue. You should now see a screen to configure a cluster. Scroll down. Make sure you see these two things:

  1. Cluster Tier is M0 Sandbox
  2. Monthly Estimate is FREE

Click on Create cluster next. You should see “Your cluster is being created”.

You have to wait for approximately 5 minutes for the cluster creation. When the cluster is ready, you’ll see this:

Now, we need to connect our Star Wars app with this cluster.

Connecting to MongoDB Atlas

Click on the Connect button.

A modal should pop up.

You need to whitelist your IP address before you can connect to your cluster. This is a security feature built into MongoDB Atlas. Go ahead and click “Add your Current IP Address”.

Next, you need to create a MongoDB user. This username and password is different from the one you used to login to MongoDB Atlas. This username and password is used ONLY for the database.

Make sure you remember MongoDB user and password. We’ll use it to connect to the database.

Next, click on choose your connection method. Select “Connect to your application” and copy the connection string.

The connection string should look something like this:

'mongodb+srv://<username>:<password>@<clustername>-rmp3c.mongodb.net/test?retryWrites=true&w=majority'

You need to replace 2 things here:

  1. Replace <username> with your Database username
  2. Replace <password> with the Database user’s password

The test in the connection string points to a test database. You would need to replace test with the name of your database if you use Mongoose. You can leave it as test if you use MongoClient like what we’re doing in this tutorial.

--

--