{ Express Router. }

Objectives:

By the end of this chapter, you should be able to:

  • Move routing logic into a separate file using the express router
  • Use the express router to refactor routing code

Router

So far we have seen how to create routes in express and render templates and even respond with redirects! As we start building more and more routes, our app.js can get very messy quickly. In order to clean this up, we will move our routes to a file in a folder called routes. The files in this folder will contain all of our routes and we will export them using the express router. Let's get started with a simple application.

RESTful Review

Let's build out routes based on these tables from earlier:

HTTP Verb Path Description CRUD
POST /users Create a user using a payload Create
GET /users Display a list of users Read
GET /users/:id Display a single user Read
PATCH or PUT * /users/:id Edit a user using a payload Update
DELETE /users/:id Delete a user Delete
HTTP Verb Path Description CRUD
GET /users/new Display a form for a new user Read
GET /users/:id/edit Display a form to edit a user Read

Building a Router

Now that we have a good structure for our RESTful routes, let's use the express router to re-create our users application. Let's get started with a new express app. In the terminal, let's run the following:

mkdir express-router && cd express-router
touch app.js
npm init -y
npm install express pug body-parser method-override
mkdir views routes
touch routes/index.js
touch views/{base,index,new,edit,show}.pug

Now let's add the following to our router/index.js

const express = require("express");
/*
  The Router is an object on the base express module.
  This router object will have similar methods (.get, .post, .patch, .delete) to the 
  app object we have previously been using.
*/
const router = express.Router();

const users = []; // this would ideally be a database, but we'll start with something simple
var id = 1; // this will help us identify unique users

// instead of app.get...
router.get("/users", (req, res, next) => {
  return res.render("index", { users }); // {users:} is ES2015 object shorthand for {users:users}
});

router.get("/users/new", (req, res, next) => {
  return res.render("new");
});

router.get("/users/:id", (req, res, next) => {
  const user = users.find(val => val.id === Number(req.params.id));
  return res.render("show", { user });
});

router.get("/users/:id/edit", (req, res, next) => {
  const user = users.find(val => val.id === Number(req.params.id));
  return res.render("edit", { user });
});

// instead of app.post...
router.post("/users", (req, res, next) => {
  users.push({
    name: req.body.name,
    id: ++id
  });
  return res.redirect("/users");
});

// instead of app.patch...
router.patch("/users/:id", (req, res, next) => {
  const user = users.find(val => val.id === Number(req.params.id));
  user.name = req.body.name;
  return res.redirect("/users");
});

// instead of app.delete...
router.delete("/users/:id", (req, res, next) => {
  const userIndex = users.findIndex(val => val.id === Number(req.params.id));
  users.splice(userIndex, 1);
  return res.redirect("/users");
});

// Now that we have built up all these routes - let's export this module for use in our app.js!
module.exports = router;

Now, how do we actually use these routes? Let's add the following in our app.js

const express = require("express");
const methodOverride = require("method-override");
const morgan = require("morgan");
const bodyParser = require("body-parser");

const app = express();
// require our routes/index.js file
const userRoutes = require("./routes");

app.set("view engine", "pug");
app.use(express.static(__dirname + "/public"));
app.use(morgan("tiny"));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(methodOverride("_method"));

// Now let's tell our app about those routes we made!
app.use(userRoutes);

app.get("/", (req, res, next) => {
  return res.redirect("/users");
});

app.listen(3000, function() {
  console.log("Server is listening on port 3000");
});

A More Declarative Router Syntax

We could also write these routes using an alternative, more declarative syntax for express routing. When we say 'more declarative' in this case, we're basically saying the code is using methods (i.e. .route('/users')) to be more readable and implicit rather than redundant and explicit. The code becomes more 'self-documenting' so to speak, because we're more concerned with what it tells us (route definitions in this case) rather than how it does it.

const express = require("express");
const router = express.Router();

const users = [];
var id = 1;

// declare the route first, then all the methods on it
router
  .route("/users")
  .get(() => {
    return res.render("index", { users });
  })
  .post(() => {
    users.push({
      name: req.body.name,
      id: ++id
    });
    return res.redirect("/users");
  });

router.route("/users/new").get((req, res, next) => {
  return res.render("new");
});

router
  .route("/users/:id")
  .get((req, res, next) => {
    const user = users.find(val => val.id === Number(req.params.id));
    return res.render("show", { user });
  })
  .patch((req, res, next) => {
    user.name = req.body.name;
    return res.redirect("/users");
  })
  .delete((req, res, next) => {
    users.splice(user.id, 1);
    return res.redirect("/users");
  });

router.route("/users/:id/edit").get((req, res, next) => {
  const user = users.find(val => val.id === Number(req.params.id));
  return res.render("edit", { user });
});

module.exports = router;

Declarative Router Syntax with a Prefix

Even better - we can prefix all of our routes to start with /users if we would like.

All we have to do is make a slight change to app.js:

// prefix every single route in here with /users
app.use("/users", userRoutes);

Here is what that looks like in our routes/index.js

const express = require("express");
const router = express.Router();

const users = [];
var id = 1;

// declare all the methods on the /users route (prefix specified in app.js)
router
  .route("")
  .get((req, res, next) => {
    return res.render("index", { users });
  })
  .post((req, res, next) => {
    users.push({
      name: req.body.name,
      id: ++id
    });
    return res.redirect("/users");
  });

router.route("/new").get((req, res, next) => {
  return res.render("new");
});

router
  .route("/:id")
  .get((req, res, next) => {
    const user = users.find(val => val.id === Number(req.params.id));
    return res.render("show", { user });
  })
  .patch((req, res, next) => {
    const user = users.find(val => val.id === Number(req.params.id));
    user.name = req.body.name;
    return res.redirect("/users");
  })
  .delete((req, res, next) => {
    const userIndex = users.findIndex(val => val.id === Number(req.params.id));
    users.splice(userIndex, 1);
    return res.redirect("/users");
  });

router.route("/:id/edit").get((req, res, next) => {
  const user = users.find(val => val.id === Number(req.params.id));
  res.render("edit", { user });
});

module.exports = router;

Sample App

You can see an example of the express router here.

Screencast

Here is a screencast to help you get set up with Express router:

When you're ready, move on to Express.js Middleware Exercises

Continue

Creative Commons License