Routing in Express.js
Express.js is a fast, unopinionated, and minimalist web framework for Node.js. It provides a robust set of features for web and mobile applications. One of its key features is routing. In this tutorial, we will be looking into this feature in detail.
What is Routing?
Routing refers to the way an application's endpoints (URIs) respond to client requests. For an introduction to routing, see the following examples in different web documents.
In Express.js, routing takes place in the following manner:
app.METHOD(PATH, HANDLER)
app
is an instance of express.METHOD
is an HTTP request method, in lowercase.PATH
is a path on the server.HANDLER
is the function executed when the route is matched.
Basic Routing
Let's start with a simple routing example. Here, we create a server that responds to a GET request at the root (/
) route.
const express = require('express')
const app = express()
const port = 3000
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.listen(port, () => {
console.log(`Example app listening at http://localhost:${port}`)
})
In the above example, app.get
is used to define a GET route. The first parameter is the path, and the second is a callback function that takes a request and a response object.
Route Paths
Route paths can be strings, string patterns, or regular expressions. The characters ?, +, *, and () are subsets of their regular expression counterparts.
Here are some examples:
// This route path will match requests to /about.
app.get('/about', function (req, res) {
res.send('About')
})
// This route path will match requests to /random.text.
app.get('/random.text', function (req, res) {
res.send('random.text')
})
// This route path will match acd and abcd.
app.get('/ab?cd', function (req, res) {
res.send('ab?cd')
})
Route Parameters
Route parameters are named URL segments that are used to capture the values specified at their position in the URL. The captured values are populated in the req.params object, with the name of the route parameter specified in the path as their respective keys.
app.get('/users/:userId/books/:bookId', function (req, res) {
res.send(req.params)
})
Route Handlers
You can provide multiple callback functions that behave like middleware to handle a request. The only exception is that these callbacks might invoke next('route') to bypass the remaining route callbacks.
app.get('/example/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello from B!')
})
Conclusion
Express.js provides a powerful routing API that allows you to map HTTP verbs to specific URL patterns, and associate those patterns with a function to run when the pattern is detected in a request. This allows you to easily build up RESTful interfaces or handle complex web routing scenarios. Keep practicing to get more understanding. Happy coding!