快递 - 获取parrent路由器的路径?

时间:2016-08-21 14:28:11

标签: node.js express

假设我想在"子文件夹"中有2个不同的实例。在网址中。在app js中,我将它定义为:

var routes = require('./routes/index');

app.use('/myapp1', routes);
app.use('/myapp2', routes);

内部路由将是相同的。

但仍然在路由器中我想"得到" app.use 中定义的路径 - 例如:myapp1,myapp2

如何在路由器中获取此信息?

来自routes / index.js:

router.use(/\/.*/, function (req, res, next) {
  // want to see "myapp1/myapp2" without the *sub* path defined in this particular router eg.: /products /user etc.
  next();
});

2 个答案:

答案 0 :(得分:1)

您可能想要使用req.baseUrl属性。

示例:

routes.get('/1', function(req, res) {
  res.send([
    req.baseUrl,
    req.path,
    req.baseUrl + req.path,
  ].join('\n'));
});

app.use('/api', routes);

/api/1发出HTTP请求将打印:

/api
/1
/api/1

答案 1 :(得分:0)

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

app.use(function(req, res, next) {
    req.appInstance = (req.url.indexOf('/app2/') == 0) ? 2 : 1; 
    next();
});

app.get('/', function(req, res, next) {
    res.redirect('/app1/user');
});

router.get('/user', function(req, res, next) {
    res.send(req.url +' on app' + req.appInstance);
});

app.use('/app1', router);
app.use('/app2', router);

app.listen(3000, function () {
    console.log('Example app listening on port 3000!');
});