【发布时间】:2015-12-12 18:11:20
【问题描述】:
我想了解 express.js 中的顺序优先级。比如下面的代码
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'
});
});
如果请求来自客户端 localhost:3000/api/abc 和 localhost:3000/user/abc,则来自 api 和 user 模块的响应。但是,如果我发出 localhost:3000/myName/xyz 之类的请求,应用程序模块会返回响应。这种行为让我关心 expressjs 的优先级是什么以及路由器模块的正确顺序是什么。为什么路由器不会混淆动作“api”、“users”和参数“:name”。请让我清楚地了解 express 是如何做的以及什么是优先级。
【问题讨论】: