从控制器

时间:2016-04-27 17:53:23

标签: express

我想访问app.get(index.js)中app.use(idCtrl.js)中定义的param。下面我有一个我的代码的简化版本。该路线有效并将我发送给控制器以获取/1234等网址,但我无法从:id访问req.params

index.js

var express = require('express');
var app     = express();
var idCtrl  = require('./idCtrl');
...
app.use('/:id([0-9]{4})', idCtrl);

idCtrl.js

var express = require('express');
var router  = express.Router();
...
router.get('/', function(req, res){
  // I wanna access :id from the app.use in index.js
});
...

1 个答案:

答案 0 :(得分:0)

处理这种情况的正确方法是

首先,设置你的参数

router.param('id',function(req,res,next,id)
{
     //d owhatever you want with your param here
     req.paramID = id; // save it in your req
     next(); // Continue to your get('/:id')
};

然后,使用参数

设置路线
router.get('/:id', function(req, res){
      console.log(req.paramID); // You got your param here
});