2017-08-08 90 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