Reputation: 34129
Based on express documentation here we can attach HTTP method to express instance, and also execute callback function when the route matches. We can also execute multiple callback route handlers. Route handlers can be in the form of a function, an array of functions, or combinations of both, as shown in the following examples.
app.get('/', function (req, res) {
res.send('GET request to the homepage');
});
or using array
var cb0 = function (req, res, next) {
console.log('CB0');
next();
}
var cb1 = function (req, res, next) {
console.log('CB1');
next();
}
var cb2 = function (req, res) {
res.send('Hello from C!');
}
app.get('/example/c', [cb0, cb1, cb2])
However,in our application i see the syntax developer has used is
app.get('/example/c',cb0, cb1)
Notice there is no array [] but 2 callback functions are passed as comma separated. This is working. But just curious how?
Upvotes: 2
Views: 5559
Reputation: 2456
In Javascript you can pass any number of arguments into a function call no matter what the function definition is. For example function x(a, b){}
could be called with more than two arguments. Programmers take advantage of the arguments special variable when they don't know in advance how many arguments a function call will receive. This is the case with the routing functions in express (.get, .put, .post, etc). They take any number of arguments you pass in and treat them as middleware functions as you can see in the documentation.
Upvotes: 3