express routing

Express Routing

Express routing refers to the process of mapping incoming requests to their respective handlers, which are responsible for generating responses. In simpler terms, it's a mechanism that allows us to define how our application will respond to requests to different URLs and HTTP methods.

To define routes in an Express application, we use the app.METHOD(PATH, HANDLER) functions, where:

  • app is an instance of the Express application.
  • METHOD is an HTTP method in lowercase (e.g. get, post, put, etc.).
  • PATH is a path on the server (e.g. '/', '/users', etc.).
  • HANDLER is a function that gets called when the specified route is requested.

Let's take a look at an example:


    const express = require('express')
    const app = express()

    app.get('/', (req, res) => {
      res.send('Hello World!')
    })

    app.listen(3000, () => {
      console.log('Server listening on port 3000')
    })
  

In this example, we're defining a route for the root path (/) using the get() method. The second argument is a callback function that gets called when the route is requested. In this case, we're simply sending a string response back to the client.

We can also define routes with parameters by using a colon before the parameter name. For example:


    app.get('/users/:id', (req, res) => {
      const id = req.params.id
      res.send(`User ID: ${id}`)
    })
  

In this case, we're defining a route for /users/:id, where :id is a parameter that can be any value. When the route is requested, we're using req.params.id to retrieve the value of the parameter from the URL.

Express routing also allows us to chain multiple handlers for a single route. This can be useful when we want to perform multiple actions before sending a response to the client. For example:


    app.get('/users/:id', (req, res, next) => {
      const id = req.params.id
      // perform some validation on id
      next()
    }, (req, res) => {
      const id = req.params.id
      // fetch user data from database
      res.send(`User data for ID: ${id}`)
    })
  

In this example, we're defining a route for /users/:id and chaining two handlers. The first handler performs some validation on the id parameter and calls the next() function to pass control to the second handler. The second handler fetches user data from a database and sends it back to the client.

Overall, Express routing provides a flexible and powerful way to handle incoming requests in our applications.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe