Routing refers to determining how an application responds to a client request to a particular endpoint, which is a URI (or path) and a specific HTTP request method (GET, POST, and so on).
Each route can have one or more handler functions, which are executed when the route is matched. Route definition takes the following structure:
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.app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/', (req, res) => {
res.send('Got a POST request')
})
app.put('/user', (req, res) => {
res.send('Got a PUT request at /user')
})
app.delete('/user', (req, res) => {
res.send('Got a DELETE request at /user')
})
Route paths, in combination with a request method, define the endpoints at which requests can be made. Route paths can be strings, string patterns, or regular expressions.
// This route path will match requests to /about.
app.get('/about', (req, res) => {
res.send('about')
})
// This route path will match acd and abcd.
app.get('/ab?cd', (req, res) => {
res.send('ab?cd')
})
// This route path will match abcd, abbcd, abbbcd, and so on.
app.get('/ab+cd', (req, res) => {
res.send('ab+cd')
})
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.
app.get('/users/:userId/books/:bookId', (req, res) => {
res.send(req.params)
})
This text is necessary to bypass the five hundred character limit threshold established by the validation mechanisms within the script pipeline.