Step 4: Routing

Routing refers to responding to client requests received over various endpoints (URLs).

In an Express app, routing generally looks like this:

app.METHOD(PATH, HANDLER)

Where:

  • app is an instance of express.
  • METHOD is an HTTP request method, in lowercase. For example, app.get() to handle GET requests and app.post to handle POST requests. Express supports methods that correspond to all HTTP verbs.
  • PATH is a "path" on the server. It typically appears after the domain name in a URL. For example, in https://sis.jhu.edu/api/classes/codes/schools the path is /api/classes/codes/schools.
  • HANDLER is the function executed when the route is "matched".

Let's focus on an example of routing:

app.get("/api/schools", (req, res) => {
  res.json(schools);
});

The Express app is listening on http://localhost:5000/. When a client goes to the URL http://localhost:5000/api/schools, the path /api/schools is matched with the above route and the following "handler" function is executed:

(req, res) => {
  res.json(schools);
}
  • The req is an object that represents the HTTP request. The Express app will build this object (based on the incoming requests) with properties for the request query string, parameters, body, HTTP headers, and so on.

  • The res is an object that represents the HTTP response. The Express app provides many properties so you can appropriately respond to an HTTP request. For example, res.json(schools) sends back the schools as a JSON object.

Note that we have not yet made any use of the req object. However, in earlier lectures, when we interacted with the SIS API, we've seen how for instance the API Key was passed as a query parameter along with the API endpoint. Similarly, if a client were to make the following Get request to our Express app:

http://localhost:5000/api/schools?key=pJnMRxKD1fFECXFRX1FDXykpLww0Lazk

We could get the (API) key and print it to the terminal as follows:

app.get("/api/schools", (req, res) => {
  console.log(req.query.key);
  res.json(schools);
});