Express Routing Basic
Routing refers to how an application’s endpoints (URIs) respond to client requests.
Basic routing
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)
Where:
-
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.
You define routing using methods of the Express app object that correspond to HTTP methods; for example, app.get() to handle GET requests and app.post to handle POST requests…etc
These routing methods specify a callback function (sometimes called “handler functions”) called when the application receives a request to the specified route (endpoint) and HTTP method.
Route methods
A route method is derived from one of the HTTP methods, and is attached to an instance of the express class.
The following code is an example of routes that are defined for the GET and the POST methods to the root of the app.
// GET method route
app.get('/', function (req, res) {
res.send('GET request to the homepage')
})
// POST method route
app.post('/', function (req, res) {
res.send('POST request to the homepage')
})
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.
Route path: /users/:userId/movies/:movieId
Request URL: http://localhost:3000/users/22/movies/2424
req.params: { "userId": "22", "movieId": "2424" }
To define routes with route parameters, simply specify the route parameters in the path of the route as shown below.
app.get('/users/:userId/movies/:movieId', 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. You can use this mechanism to impose pre-conditions on a route, then pass control to subsequent routes if there’s no reason to proceed with the current route.
Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
A single callback function can handle a route. For example:
//1.Use the express module
var express = require('express');
//2.Create an object of the epxpress module
var app = express();
app.get('/default', function (req, res) {
res.send('Single Callback Page!')
})
var server = app.listen(3000, function() {
console.log('Listening Port : 3000 ');
});
More than one callback function can handle a route (make sure you specify the next object). For example:
What is this next()?
A middleware is basically a function that will the receive the Request and Response objects, just like your route Handlers do. As a third argument you have another function which you should call once your middleware code completed. This means you can wait for asynchronous database or network operations to finish before proceeding to the next step.
If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging
//1.Use the express module
var express = require('express');
//2.Create an object of the epxpress module
var app = express();
app.get('/', function (req, res) {
res.send('Hello Response From Index Page !')
})
app.get('/home/a', function (req, res) {
res.send('Hello Response From Page A!')
})
app.get('/about/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, function (req, res) {
res.send('Hello Response From Page B!')
})
var server = app.listen(3000, function() {
console.log('Listening Port : 3000 ');
});
The above code can be written like below
Here the variable funb will have the function definition and the variable used as a parameter in the route ‘/user/b’ with next().
//1.Use the express module
var express = require('express');
//2.Create an object of the express module
var app = express();
app.get('/user/a', function (req, res) {
res.send('Hello from A!')
})
var funb = function (req, res, next) {
console.log('Text from B!');
next()
};
app.get('/user/b', function (req, res, next) {
console.log('the response will be sent by the next function ...')
next()
}, funb, function (req, res) {
console.log('Text from C!');
res.send('Text From BC !')
})
var server = app.listen(3000, function () {
console.log('Listening Port : 3000 ');
});