express.js中路由器优先级的顺序

我想了解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和用户模块的响应。但是,如果我发出类似localhost:3000 / myName /

xyz的请求,则应用程序模块将返回响应。此行为使我担心expressjs的优先顺序以及路由器模块的正确顺序是什么。为什么路由器不会在动作“

api”,“用户”和参数“:name”之间造成混淆。请让我清楚地理解表达的方式和优先顺序。

回答:

顺序是先到先得。

在您的情况下,如果用户点击/ api,他将获得api的响应,但是如果您/:name在之前编写route

/api/:name/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'

});

});

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'

});

});

以上是 express.js中路由器优先级的顺序 的全部内容, 来源链接: utcz.com/qa/418246.html

回到顶部