如何将参数传递给express.js路由器? [英] How do I pass a parameter to express.js Router?

查看:51
本文介绍了如何将参数传递给express.js路由器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是Express.js的路由指南中的修改示例:

Here's a modified example from Express.js's routing guide:

var express = require('express');
var router = express.Router();

router.get('/', function(req, res) {
  res.send('Birds home page');
});

router.get('/about', function(req, res) {
  res.send('About birds');
});

...
app.use('/birds', router);
app.use('/fish', router);

当我同时访问/birds/about /fish/about 时,这将打印关于鸟类".

This prints "About birds" when I visit both /birds/about and /fish/about.

如何将参数或其他内容传递给路由器,以便在控制器功能中可以区分出这两个不同的路由?

How do I pass a parameter or something to the router so, in the controller functions, it can tell those two different routes apart?

例如,我想在访问/birds/about 时看到鸟可以飞",而在访问/fish/about 时看到鱼可以游泳".

For example, I'd like to see "Birds can fly" when visiting /birds/about and "Fish can swim" when visiting /fish/about.

理想情况下,我希望能够传递一些配置对象",因此迷你应用程序不需要知道可能会挂载在其上的所有可能路由(以伪代码):

Ideally, I'd like to be able to pass some "configuration object" so the mini-app does not need to know about all possible routes it may be mounted at (in pseudocode):

    router.get('/about', function(req, res) {
      res.send(magic_configuration.about_text);
    });
   ....
   magically_set_config(router, {about_text: "Bears eat fish"})
   app.use('/bears', router);

推荐答案

这就是我想出的:我将迷你应用程序配置"分配给 req :

Here's what I've come up with: I pass the "mini-app configuration" by assigning it to req:

app.use('/birds', function (req, res, next) {
    req.animal_config = {
        name: 'Bird',
        says: 'chirp'
    };
    next();
}, animal_router);

app.use('/cats', function (req, res, next) {
    req.animal_config = {
        name: 'Cat',
        says: 'meow'
    }
    next();        
}, animal_router);

然后在我的路线中可以访问它们:

and then in my route I can access them:

var express = require('express');
var router = express.Router();

...

router.get('/about', function(req, res) {
  var animal = req.animal_config;
  res.send(animal.name + ' says ' + animal.says);
});

这种方法可以轻松地将迷你应用程序"安装在提供不同配置的另一个位置,而无需修改应用程序的代码:

This approach allows to easily mount the "mini-app" at another location providing different configuration, without modifying the code of the app:

app.use('/bears', function (req, res, next) {
    req.animal_config = {
        name: 'Bear',
        says: 'rawr'
    };
    next();
}, animal_router);

这篇关于如何将参数传递给express.js路由器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆