Express, the web framework for Node.js

Viswesh Subramanian
JavaScript Store
Published in
6 min readMar 1, 2018

Express is the most popular web framework used with Node.js. In this article, I will teach you how to use express.js by showing you solid examples and code blocks to create web servers and HTTP API’s. At the end of the article, you will be transformed from being a novice into an Express Ninja!

Lets get started!

Setup

  1. Like all things Node js, it all starts with “npm init”. Open up your terminal, “npm init”
  2. npm install express –save
  3. Now that we have express downloaded in our node_modules directory, we are all set to create our web server.
  4. Create a new file app.js at the root of the working directory

Create Web servers

In app.js, let’s bring in express and stand up a web server which displays “Express — Fast, unopinionated, minimalist web framework for Node.js”

const express = require('express');

const app = express();

app.get('/',(req, res)=>{
res.send('<h1>Express - Fast, unopinionated, minimalist web framework for Node.js</h1>');
});

app.listen(3030, ()=>{
console.log('server is up');
});

By invoking express(), we create a new express instance and all further configuration and setup are upon the created instance. Creating routes, or in other words, defining what should happen when a user clicks home or about or contact link is as simple as providing a callback. req is the Request object and res is the Response object. In the above code block, we send an HTML to be displayed when a user hits https://localhost:3030/. Finally, we define on what port our web server must listen on. To start the web server — “node app.js”

For projects which do not require a backend and its just a bunch of static files, express provides an inbuilt middleware to serve up resources.

app.use(express.static(path.join(__dirname, 'public')))

Yes, it is not rocket science to serve static sites.

Next up, Templates! Templates are an integral part of web servers and express offers compatibility with a plethora of template engines. With a template engine in place, static templates can be replaced with dynamic or runtime values.

First, define the location of all your templates and set the templating engine. Let’s use handlerbars — it’s a popular templating library. npm install hbs –save

const hbs = require('hbs'); app.set('views', __dirname + '/views'); app.set('view engine','hbs'); //Sets template engine

Create index.hbs under views/ directory

<h1>{{title}}</h1> 
<p>{{message}}</p>

Your directory structure must look like –

.
├── app.js
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
└── views
├── index.hbs

Now that we have informed express about our ‘views’ location, updating template variables with runtime information are as simple as providing the template an object.

app.get('/', function (req, res) {
res.render('index', { title: 'Express', message: 'Node.js web application framework.' })
})

For templating newbies, I highly recommend that you check out handlebars documentation to get familiar with whats possible.

If you are following along,✋

Enter the world of partials — Once you get on with creating multiple pages, say products.hbs and contacts.hbs, you might get into a situation where you are duplicating HTML tag blocks. To align with the ‘DRY’ principle and also for maintenance sake, we can create partials.

hbs.registerPartials(__dirname+'/views/partials')

By registering the location with hbs, we can now reuse partial HTML blocks in our pages.

For example, if want to extract ‘contact’ and reuse at multiple pages, create ‘partials’ directory under views and place your HTML.

contact.hbs

<form> 
//First name, Last name
//Email
</form>

products.hbs

<h1>{{title}}</h1> 
<p>{{message}}</p>
{{> contact}}

contacts.hbs

<h1>{{title}}</h1> 
<p>{{content}}</p>
{{> contact}}

Create RESTful APIs

In this section, I show you how to create RESTful APIs on top of MongoDB database. Create another file — server.js to host all of the RESTful APIs at the root of the working directory. Before getting started, install 2 new node modules — mongoose and body-parser. Mongoose is an object modeling tool for mongodb and body-parser helps to parse incoming requests.

const express = require('express');
const bodyParser = require('body-parser');
const mongoose = require('mongoose');

const app = express();

app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

let router = express.Router();

router.get('/', (req, res)=>{
res.json({
name: "Good to go!"
})
});

app.use(router);

app.listen(3030, ()=>{
console.log('server is up');
});

With the above code block, hitting http://localhost:3030/ will get {name: “Good to go!”}. If you get the response, you are on the right track. You can either send a curl request, open the link in a browser or use Postman, the REST tool.

Pro tip: If no response comes back, make sure the app is using the router -app.use(router)

It’s time to set up our Mongo database. Follow the direction at MongoDB website and ensure the mongod service is up and running.

For the purpose of learning, we are going to connect to a videos database with a movies collection and with express routes, we are going to create the following routes-

/movies             GET    List all movies
/movies POST Create a movie
/movies/:movie_id GET Get the movie
/movies/:movie_id PUT Update the movie
/movies/:movie_id DELETE Delete the movie

Before moving further, mongoose requires a model for the collection. Create models directory at the root with a model file movie.js

const mongoose     = require('mongoose');
const Schema = mongoose.Schema;

let MovieSchema = new Schema({
title: String,
year: String
});

module.exports = mongoose.model('Movie', MovieSchema);

Now, include the exported model at server.js and connect mongoose with mongoDB.

const Movie = require('./models/movie'); mongoose.connect('mongodb://localhost:27017/video');

Your directory structure should look like this –

.
├── app.js
├── server.js
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ └── stylesheets
│ └── style.css
└── models
├── movie.js
└── views
├── index.hbs

GET

Chain a route ‘/movies’ on the express router we previously created.

router.route('/movies')
.get((req, res)=>{
Movie.find((err, movies)=>{
if(err){
res.send(err);
}
res.json(movies);
});
});

Open up POSTMAN and GET http://localhost:3030/movies/. You will get an empty array because there is no data in the collection. Lets fix that by creating an API to POST data.

router.route('/movies')
.get((req, res)=>{
...
})
.post((req,res)=> {
let movie = new Movie();
movie.title = req.body.title;
movie.year = req.body.year;

movie.save((err)=> {
if (err) {
res.send(err);
}
res.json({message: 'Movie successfully created!'})
})
});

To post a new movie, open up POSTMAN and send a POST request

Go ahead and create a couple of more movies with ‘title’ and ‘year’ in Body and finally verify ‘GET’ api.

So far, we learned how to GET & PUT movies. Let’s move on to create routes for ‘a’ movie.

To create a route for a single item, we chain the middleware function on a route with an id –

router.route('/movies/:movie_id')
.get((req, res)=>{
Movie.findById(req.params.movie_id, (err, movie)=>{
if(err){
res.send(err);
}
res.json(movie);
})
});

Go ahead and test the API in POSTMAN. Did the API return the right movie?

Next up, update API with PUT verb.

router.route('/movies/:movie_id')
.get((req, res)=>{
...
})
.put((req, res)=>{
Movie.findById(req.params.movie_id, (err, movie)=>{
if(err) {
res.send(err);
}
movie.title = req.body.title;
movie.year = req.body.year;

movie.save((err)=>{
if(err) {
res.send(err);
}
res.json({message: 'Movie successfully updated!'});
})
})
});

The last API is to delete a movie

router.route('/movies/:movie_id')
.get((req, res)=>{
...
})
.put((req, res)=>{
...
})
.delete((req, res)=>{
Movie.remove({
_id: req.params.movie_id
}, (err, movie)=>{
if(err) {
res.send(err);
}
res.json({message: 'Movie successfully deleted!'});
})
});

That’s about it, folks! Pat yourself on the back if you were successful with GET, POST, PUT and DELETE.

To recap, you learned how to create a web server with express to serve static sites as well as custom routes. You also learned how to create RESTful APIs using Express routes. There is much more to handling requests but this should serve as a solid foundation.

Originally published at javascriptstore.com on March 1, 2018.

--

--

Viswesh Subramanian
JavaScript Store

Full stack JS developer. Software generalist for the most part.