[英]Dynamic path in express routes
我想知道如何动态地使用表达路径。 例如,我正在使用lodash在regex方法中查找不同文件中的路径。
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") }) })
在上面的代码中,我只是嵌套了路由。 但没有任何回应。 有没有办法做到这一点? 如果需要,我也想使用此方法。 不管怎么说,还是要谢谢你
使用中间件是不可能的。 当请求到来时,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.use
或routes.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") }) */
参考: 构建服务API第4部分
无论如何,如果这种方法有问题,请留言我:D
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.