How to use routing in Express.js

I will introduce how to create a routing process with Express.js. The code will also be posted on Git Hub, so please refer to it.

overview

Express.js provides features that allow you to easily define routes. Routing is defined by specifying endpoints for handling HTTP requests.

Below, we’ll explore routing concepts, defining routes, creating route handlers, handling routing parameters, and options for routes in more detail.

Here, we will explain the routing method using the following versions.

Express v4.18.1
nodejs v19.7.0

In addition, all the code created this time is posted on GitHub.

Routing concepts

Routing defines how an Express.js application handles requests from clients when they reach a particular endpoint.

Routing is defined by a combination of HTTP methods (GET, POST, PUT, DELETE, etc.) and paths (URLs).

How to define routes

There are several ways to use routing, but the four most common are:

  1. How to use the app method
app.<HTTP method>('<path>', (req, res) => {
  // handling routes
});
  1. How to use the Router object
const router = express.Router();

router.<HTTP method>('<path>', (req, res) => {
  // handling routes
});

app. use(router);
  1. How to use the route handler function directly
const routeHandler = (req, res) => {
  // handling routes
};
app.<HTTP method>('<path>', routeHandler);
  1. How to use rootchain
app.route('<path>')
  .get((req, res) => {
    // handle GET requests
  })
  .post((req, res) => {
    // handle the POST request
  });
  • HTTP method: Specify the HTTP request method (eg get, post, put, delete, etc.).
  • Path: Specifies the URL path that requests from clients will match.

From the heading below, write the code.

How to use the app method

appMethod.js

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

app.use(express.json());

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

app.post("/users", (req, res) => {
  const user = req.body;
  // user creation, etc...
  res.json({ id: 1, name: user.name });
});

app. put("/users/:id", (req, res) => {
  const userId = req.params.id;
  const user = req.body;
  // user updates, etc...
  res.json({ id: userId, name: user.name });
});

app.delete("/users/:id", (req, res) => {
  const userId = req.params.id;
  // user deletion etc...
  res.json({ message: `User ${userId} has been deleted.` });
});

app.listen(3000, () => {
  console.log("Server started on port 3000");
});

Commentary

  • Import Express module and create application
const express = require("express");
const app = express();

This part loads the Express module and creates a new Express application instance.

  • register middleware
app.use(express.json());

This allows Express applications to parse JSON-formatted request bodies.

  • GET request handler
app.get("/hello", (req, res) => {
  res.send("Hello, Express!");
});

This will cause the server to respond to a GET request to “/hello” with “Hello, Express!”.

  • POST request handler
app.post("/users", (req, res) => {
  const user = req.body;
  // user creation, etc...
  res.json({ id: 1, name: user.name });
});

With this, a POST request to “/users” will attempt to create a new user and, if successful, return the user information in JSON format.

  • PUT request handler
app. put("/users/:id", (req, res) => {
  const userId = req.params.id;
  const user = req.body;
  // user updates, etc...
  res.json({ id: userId, name: user.name });
});

With this, a PUT request to “/users/:id” will attempt to update the user with the specified id, and upon success will return the updated user information in JSON format.

  • DELETE request handler
app.delete("/users/:id", (req, res) => {
  const userId = req.params.id;
  // user deletion etc...
  res.json({ message: `User ${userId} has been deleted.` });
});

With this, a DELETE request to “/users/:id” will attempt to delete the user with the specified id and, if successful, will return a message in JSON format stating that the user has been deleted.

  • Start server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

This part sets the server to listen on port 3000. After the server starts, you should see the message “Server started on port 3000” on the console.

This code uses Express to define multiple path handlers for different HTTP methods and registers them with the Express server. Each handler receives a request, performs appropriate processing, and returns a response.

test

# test GET request
curl -X GET http://localhost:3000/hello
# test the POST request
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe"}' http://localhost:3000/users
# test the PUT request
curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane Smith"}' http://localhost:3000/users/1
# test DELETE request
curl -X DELETE http://localhost:3000/users/1

How to use the Router object

routerObject.js

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

router.use(express.json());

router.get("/hello", (req, res) => {
  res.send("Hello, Express!");
});

router.post("/users", (req, res) => {
  const user = req.body;
  // user creation, etc...
  res.json({ id: 1, name: user.name });
});

router.put("/users/:id", (req, res) => {
  const userId = req.params.id;
  const user = req.body;
  // user updates, etc...
  res.json({ id: userId, name: user.name });
});

router.delete("/users/:id", (req, res) => {
  const userId = req.params.id;
  // user deletion etc...
  res.json({ message: `User ${userId} has been deleted.` });
});

app. use(router);

app.listen(3000, () => {
  console.log("Server started on port 3000");
});

Commentary

  • Import Express module and create application and router
const express = require("express");
const app = express();
const router = express.Router();

The code above loads the Express module and creates an instance of the Express application and router.

  • register middleware
router.use(express.json());

This allows the router to parse the JSON-formatted request body.

  • GET request handler
router.get("/hello", (req, res) => {
  res.send("Hello, Express!");
});

Returns the message “Hello, Express!” as a response to a GET request to the “/hello” endpoint.

  • POST request handler
router.post("/users", (req, res) => {
  const user = req.body;
  // user creation, etc...
  res.json({ id: 1, name: user.name });
});

Create a new user in response to a POST request to the “/users” endpoint and return the created user’s information in JSON format as a response.

  • PUT request handler
router.put("/users/:id", (req, res) => {
  const userId = req.params.id;
  const user = req.body;
  // user updates, etc...
  res.json({ id: userId, name: user.name });
});

In response to a PUT request to the “/users/:id” endpoint, update the user with the specified ID and return the updated user information in JSON format as a response.

  • DELETE request handler
router.delete("/users/:id", (req, res) => {
  const userId = req.params.id;
  // user deletion etc...
  res.json({ message: `User ${userId} has been deleted.` });
});

Deletes the user with the specified ID in response to a DELETE request to the “/users/:id” endpoint, and returns a message in JSON format indicating that the user has been deleted.

  • Registration in the application of the router
app. use(router);

Register the router with your application. This makes the endpoints defined in the router available to your application.

  • Start server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

This part sets the server to listen on port 3000. After the server starts, you should see the message “Server started on port 3000” on the console.

This code uses Express to define multiple path handlers for different HTTP methods and registers them with the Express server. Each handler receives a request, performs appropriate processing, and returns a response.

test

# test GET request
curl -X GET http://localhost:3000/hello
# test the POST request
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe"}' http://localhost:3000/users
# test the PUT request
curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane Smith"}' http://localhost:3000/users/1
# test DELETE request
curl -X DELETE http://localhost:3000/users/1

How to use the route handler function directly

handler.js

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

const helloHandler = (req, res) => {
  res.send("Hello, Express!");
};

const userPostHandler = (req, res) => {
  const user = req.body;
  // user creation, etc...
  res.json({ id: 1, name: user.name });
};

const userPutHandler = (req, res) => {
  const userId = req.params.id;
  const user = req.body;
  // user updates, etc...
  res.json({ id: userId, name: user.name });
};

const userDeleteHandler = (req, res) => {
  const userId = req.params.id;
  // user deletion etc...
  res.json({ message: `User ${userId} has been deleted.` });
};

app.get("/hello", helloHandler);
app.post("/users", userPostHandler);
app.put("/users/:id", userPutHandler);
app.delete("/users/:id", userDeleteHandler);

app.listen(3000, () => {
  console.log("Server started on port 3000");
});

Commentary

  • Import Express module and create application
const express = require("express");
const app = express();

The code above loads the Express module and creates a new Express application instance.

  • define handler function
const helloHandler = (req, res) => {
  res.send("Hello, Express!");
};

const userPostHandler = (req, res) => {
  const user = req.body;
  // user creation, etc...
  res.json({ id: 1, name: user.name });
};

const userPutHandler = (req, res) => {
  const userId = req.params.id;
  const user = req.body;
  // user updates, etc...
  res.json({ id: userId, name: user.name });
};

const userDeleteHandler = (req, res) => {
  const userId = req.params.id;
  // user deletion etc...
  res.json({ message: `User ${userId} has been deleted.` });
};

Here, each HTTP method and endpoint are defined as functions.

  • Register route
app.get("/hello", helloHandler);
app.post("/users", userPostHandler);
app.put("/users/:id", userPutHandler);
app.delete("/users/:id", userDeleteHandler);

We tie each function to a specific endpoint and HTTP method.

  • Start server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

This part sets the server to listen on port 3000. After the server starts, you should see the message “Server started on port 3000” on the console.

test

# test GET request
curl -X GET http://localhost:3000/hello
# test the POST request
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe"}' http://localhost:3000/users
# test the PUT request
curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane Smith"}' http://localhost:3000/users/1
# test DELETE request
curl -X DELETE http://localhost:3000/users/1

How to use root chain

chain.js

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

app.use(express.json());

app.route("/users/:id")
  .get((req, res) => {
    const userId = req.params.id;
    // get user etc...
    res.json({ id: userId, name: "John Doe" });
  })
  .post((req, res) => {
    const user = req.body;
    // user creation, etc...
    res.json({ id: 1, name: user.name });
  })
  .put((req, res) => {
    const userId = req.params.id;
    const user = req.body;
    // user updates, etc...
    res.json({ id: userId, name: user.name });
  })
  .delete((req, res) => {
    const userId = req.params.id;
    // user deletion etc...
    res.json({ message: `User ${userId} has been deleted.` });
  });

app.listen(3000, () => {
  console.log("Server started on port 3000");
});

Commentary

  • Import Express module and create application
const express = require("express");
const app = express();

This part loads the Express module and creates a new Express application instance.

  • register middleware
app.use(express.json());

This allows Express applications to parse JSON-formatted request bodies.

  • chain of route handlers
app.route("/users/:id")
  .get((req, res) => {
    const userId = req.params.id;
    // get user etc...
    res.json({ id: userId, name: "John Doe" });
  })
  .post((req, res) => {
    const user = req.body;
    // user creation, etc...
    res.json({ id: 1, name: user.name });
  })
  .put((req, res) => {
    const userId = req.params.id;
    const user = req.body;
    // user updates, etc...
    res.json({ id: userId, name: user.name });
  })
  .delete((req, res) => {
    const userId = req.params.id;
    // user deletion etc...
    res.json({ message: `User ${userId} has been deleted.` });
  });

This allows you to chain a series of request handlers for a particular route. Here, we set up GET, POST, PUT, and DELETE request handlers for the route “/users/:id”.

  • Start server
app.listen(3000, () => {
  console.log("Server started on port 3000");
});

This part sets the server to listen on port 3000. After the server starts, you should see the message “Server started on port 3000” on the console.

test

# test GET request
curl -X GET http://localhost:3000/users/1
# test the POST request
curl -X POST -H "Content-Type: application/json" -d '{"name":"John Doe"}' http://localhost:3000/users/1
# test the PUT request
curl -X PUT -H "Content-Type: application/json" -d '{"name":"Jane Smith"}' http://localhost:3000/users/1
# test DELETE request
curl -X DELETE http://localhost:3000/users/1

summary

In this article, we’ve seen how to use routing with Express.js. Below is a summary of the main points.

Direct use of route handler functions: Express.js allows direct use of handler functions for specific HTTP methods and paths. This allows you to define how requests should be handled when they reach a particular endpoint.

Using route chaining: Express.js allows you to chain multiple HTTP methods to the same path using the app.route() method. This allows you to centrally manage different HTTP methods for the same path while avoiding code duplication.

By using these methods, you can efficiently manage routing in your Express.js application. It is important to use each method appropriately according to your specific situation and requirements.