2017-10-15 235 views
2

我想知道如何動態地使用路徑。例如,我使用lodash在正則表達式方法中找到不同文件中的路徑。快速路線中的動態路徑

routes.js 

const json = require('./routes.json') 
 
const _ = require('lodash') 
 
routes.use(function(req, res, next) { 
 

 
    let str = req.path 
 
    let path = str.split('/')[1] 
 

 
    // [Request] => /test/123 
 
    console.log(path) 
 
    // [Result] => test 
 

 
    let test = _.find(json.routes, function(item) { 
 
    return item.path.match(new RegExp('^/' + path + '*')) 
 
    }) 
 
    console.log(test) 
 
    //{"path" : "/test/:id", "target" : "localhost:2018", "message" : "This is Test Response" }, 
 

 
    routes.get(test.path, function(req, res) { 
 
    res.json("Done") 
 
    }) 
 
})

在上面的代碼中,我只是嵌套的路由。但沒有任何迴應。有沒有辦法做到這一點?這個方法也是我想用DB和必要的。無論如何感謝

回答

0

使用中間件是不可能的。當請求到達時,expressjs將首先搜索已註冊的路徑。 所以,我們來看看爲什麼代碼不能正常運行。

例如,我作爲一個用戶請求:localhost:2018/test/123

請跟隨我的評論下面

const json = require('./routes.json') 
 
const _ = require('lodash') 
 
routes.use(function(req, res, next) { 
 

 
    let str = req.path 
 
    let path = str.split('/')[1] 
 

 
    // [Request] => /test/123 
 
    console.log(path) 
 
    // [Result] => test 
 

 
    let test = _.find(json.routes, function(item) { 
 
    return item.path.match(new RegExp('^/' + path + '*')) 
 
    }) 
 
    console.log(test) 
 
    //{"path" : "/test/:id", "target" : "localhost:2018", "message" : "This is Test Response" }, 
 

 
    //And now, the routes has been registered by /test/:id. 
 
    //But, you never get response because you was hitting the first request and you need a second request for see if that works. But you can't do a second request, this method will reseting again. Correctmeifimwrong 
 

 
    routes.get(test.path, function(req, res) { 
 
    res.json("Done") 
 
    }) 
 
})

如何接近這個目標呢?但是,我們需要在app.useroutes.use內註冊我們的路線。到目前爲止,我得到了,我們可以在這裏使用循環。

//Now, we registering our path into routes.use 
 
_.find(json.routes, function(item) { 
 
    routes.use(item.path, function(req, res) { 
 
    res.json("Done") 
 
    }) 
 
}) 
 

 
//The result become 
 

 
/** 
 
* routes.use('/test:id/', function(req, res, next){ 
 
    res.json("Done") 
 
}) 
 

 
routes.use('/hi/', function(req, res, next){ 
 
    res.json("Done") 
 
}) 
 

 
*/

參考:Building a service API Part 4

還是要謝謝你,給我留下了評論,如果有什麼東西錯用這種方法:d