Routing & Redirects in Express

Route is an important component of a website. It helps the website know where the user is going to the website, thereby responding appropriately.

In Express, routes are built-in and easy to use. In this article, let’s learn about routes in Express.

I. Routing in Express

Routing in Node.js determines how the application will respond when a user makes a request to a particular endpoint.

That endpoint is usually a URI or a path (Path) with a specific request method (POST, PUT, GET, DELETE)

In express.js routing has the following structure

app.METHOD(Path, Handler...)
  • app : is an instance of express
  • METHOD: is an HTTP Method
  • Path: is a path on the server.
  • Handler: a callback function that will execute when a route is matched

Example

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

II. Route methods

Express supports many different types of HTTP methods, and GET, POST, PUT, DELETE are the most used.

// respond with "Hello World!" on the homepage
app.get("/", function (req, res) {
  res.send("Hello World!");
});

// accept POST request on the homepage
app.post("/", function (req, res) {
  res.send("Got a POST request");
});

// accept PUT request at /user
app.put("/user", function (req, res) {
  res.send("Got a PUT request at /user");
});

// accept DELETE request at /user
app.delete("/user", function (req, res) {
  res.send("Got a DELETE request at /user");
});

With the above declaration, when we access the address localhost:3000/user by GET, POST, PUT, DELETE methods, the server will send back a corresponding text.

When we access /hello, then the route will match and the function will be called.

III. Route paths

Route paths can be strings, string patterns, or regular expressions.

  • /public/post: is a regular path
  • /public/user/*: is a path with the symbol * representing any string
  • /.*hello$/: is a path in the form of a regex.

Example 1: String pattern

The * symbol here means that the above route matches all paths starting with /users/.

app.get("/users/*", (req, res) => {
  // Do something.
});

Example 2:

This is a path with a regular expression. This route will match any path ending with hello.

app.get(/.*hello$/, (req, res) => {
  // Do something.
});

IV. Routing Parameters

Route parameters are named URL segments that can retrieve the corresponding values.

// Get user's info by id
app.get("/user/:id", (req, res) => {
  let id = req.params["id"];
  res.send("The id is " + id);
});

With the above declaration, when we access the address localhost:3000/user/125, the server will return you the text: The id is 125.

V. Response methods

In express, there are some response methods:

  • res.json(): Returns a JSON data
  • res.redirect(): Redirects to a certain path
  • res.render(): Returns a view template
  • res.send(): sends data as text

Example responses

1. Send simple HTML text

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>");
});

2. Send 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 });
});

3. 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");
});

4. 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 });
});