Order of router precedence in express.js
I would like to understand the order precedence in express.js. For example, as bellow code
var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
app.use('/api', api);
app.use('/users', users);
app.use('/:name', function(req, res, next) {
console.log('from app.js name:', req.params.name);
res.render('index', {
title: req.params.name
});
}, routes);
app.use('/', function(req, res, next) {
res.render('index', {
title: 'MainPage'
});
});
If a request come from client localhost:3000/api/abc and localhost:3000/user/abc, the response from api and user module. But if I make a request like localhost:3000/myName/xyz, the app module return a response. This behavior let me concern about what is precedence of expressjs and what is correct order for router modules. Why routers do not confuse between actions "api", "users" and parameter ":name". Please let me understand clearly how express does and what is precedence.
The order is first come first serve.
In your case, if user hits /api, he will get response from api, but if you write /:name
route before /api
, /:name
will serve for /api
requests also.
Case1:
/api
will serve requests for/api
.
var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
app.use('/api', api);
app.use('/users', users);
app.use('/:name', function(req, res, next) {
console.log('from app.js name:', req.params.name);
res.render('index', {
title: req.params.name
});
}, routes);
app.use('/', function(req, res, next) {
res.render('index', {
title: 'MainPage'
});
});
Case2:
/:name
serves requests for/api
and/users
var routes = require('./routes/index');
var users = require('./routes/users');
var api = require('./routes/api');
app.use('/:name', function(req, res, next) {
console.log('from app.js name:', req.params.name);
res.render('index', {
title: req.params.name
});
}, routes);
app.use('/api', api);
app.use('/users', users);
app.use('/', function(req, res, next) {
res.render('index', {
title: 'MainPage'
});
});
The example given in the ExpressJS documentation is pretty simple and was unfortunately difficult to find. I only found it through another SO question.
Middleware functions are executed sequentially, therefore the order of middleware inclusion is important
app.use(function(req, res, next) {
res.send('This is the only thing that ever happens')
}
app.use(...) // never used
app.get(...) // never used
app.put(...) // never used
app.post(...) // never used