Routing & Redirects in Express

In Express, to send simple HTML text, we can use .send() method:

const express = require("express");

// express app
const app = express();

// listen for requests
app.listen(3000);

app.get("/", (req, res) => {
  res.send("<p>home page</p>");
});

app.get("/about", (req, res) => {
  res.send("<p>about page</p>");
});

However, if we have HTML pages, we’ll need to use another option. How to do that?

I. Routing HTML Pages

To provide routing in Express, we use sendFile() method. By default, it’ll look for an absolute path from the root of our computer.

If we provide relative path, we’ll need to tell where it’s relative from.

To do that, we pass in { root: __dirname } object as a second argument to specify what the root should be.

const express = require("express");

// express app
const app = express();

// listen for requests
app.listen(3000);

app.get("/", (req, res) => {
  res.sendFile("./views/index.html", { root: __dirname });
});

app.get("/about", (req, res) => {
  res.sendFile("./views/about.html", { root: __dirname });
});

II. Redirects

To redirect pages in Express, we can use redirect() method. Also, it automatically sets the status code.

For example, we redirect “about-us” page to “about” page:

// redirects
app.get("/about-us", (req, res) => {
  res.redirect("/about");
});

III. 404 page

To set an 404 page in Express, we use the use() method. We use this method to create Middleware and fire Middleware functions in Express.

In this case, we pass in a callback function that sets a status code to 404 and send a 404.html file to the browser.

// 404 page
app.use((req, res) => {
  res.status(404).sendFile("./views/404.html", { root: __dirname });
});

Because Express doesn’t realize we’re sending an 404 page, we must include the status() method manually.

Note

When we type an address in the browser, Express will check every route. If none matches, it will return a 404 page.

Therefore, the position of 404 route must be placed at the end of the routes.

const express = require("express");

// express app
const app = express();

// listen for requests
app.listen(3000);

app.get("/", (req, res) => {
  res.sendFile("./views/index.html", { root: __dirname });
});

app.get("/about", (req, res) => {
  res.sendFile("./views/about.html", { root: __dirname });
});

// redirects
app.get("/about-us", (req, res) => {
  res.redirect("/about");
});

// 404 page
app.use((req, res) => {
  res.status(404).sendFile("./views/404.html", { root: __dirname });
});