简体   繁体   English

快速路线中的动态路径

[英]Dynamic path in express routes

I wonder how to using path in express dynamically. 我想知道如何动态地使用表达路径。 For example, i'm using lodash for finding a path in different file with regex method. 例如,我正在使用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") }) }) 

On above code, i just nested the routes. 在上面的代码中,我只是嵌套了路由。 But there's nothing any response. 但没有任何回应。 Is there any ways to do this? 有没有办法做到这一点? This method also i want to use with DB if necessary. 如果需要,我也想使用此方法。 Thanks anyway 不管怎么说,还是要谢谢你

Using middleware is impossible. 使用中间件是不可能的。 When a request comes, expressjs will search a registered path first. 当请求到来时,expressjs将首先搜索已注册的路径。 So here we go why that code not running as well. 所以我们在这里解释为什么代码运行不正常。

For example, I'm as an user request : localhost:2018/test/123 例如,我是一个用户请求: localhost:2018/test/123

Please following my comment in below 请关注我的评论

 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") }) }) 

How to approach this goal then? 那么如何实现这个目标呢? However, we need a registering our routes inside app.use or routes.use . 但是,我们需要在app.useroutes.use注册我们的路由。 So far what i got, we can using loop in here. 到目前为止,我得到了,我们可以在这里使用循环。

 //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") }) */ 

Reference : Building a service API Part 4 参考: 构建服务API第4部分

Thanks anyway, leave me a comment if there's something wrong with this method :D 无论如何,如果这种方法有问题,请留言我:D

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM