高速路线中的dynamicpath

我不知道如何dynamic地使用path。 例如,我正在使用lodash在正则expression式方法中find不同文件中的path。

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和必要的。 不pipe怎么说,还是要谢谢你

使用中间件是不可能的。 当请求到来时,expressjs将首先search已注册的path。 所以在这里我们去为什么代码不运行。

例如,我作为一个用户请求: 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") }) })