2017-08-08 108 views
0

在app.js中,我需要处理下面几个类似的路线。如何访问函数中的路径?

app.get('/path1', function(req, res) { 
    var path = some_processing_based_on_path('/path1'); 
    res.render(path); 
} 

我想将它们“挤”成一条常见的路线。这是我的想法。

app.get('/path*', function(req, res) { 
    var path = some_processing_on_path(???); 
    res.render(path); 
} 

基本要求:能够访问函数中的路径。

回答

2

可以使用req.path获得请求的路径:

app.get('/path*', function(req, res) { 
    var path = some_processing_on_path(req.path) 
    res.render(path) 
}) 

您还可以使用req.params访问名为路径参数:

app.get('/path:id', function(req, res) { 
    var path = some_processing_on_path(req.params.id) 
    res.render(path) 
}) 
+0

非常好,谢谢! – user180574

0

你可以传递一个函数到你的控制器,然后为所有要使用的控制器定义该功能。

这里有一个例子:

module.exports = function (app, insecureApp) { 

    router.post('/your/path/modification', upsert); 
    router.put('/your/path/modification/2', upsert); 
    function upsert(req, res, next) { 
     model.findOneAndUpdate({_id: req.body.name}, req.body, {upsert: true}, function (err, docs){ 
      if (err) return next(err); 
      res.json("document successfully updated"); 
     }); 
    } 

    // apply this router to the following path 
    app.use('/your/base/path/here', router); 
}; 
0

尝试特殊符号即 app.get ('/path\*',...)

前添加转义字符,你可以访问路径:req.path