快速路线中的动态路径
问题描述:
我想知道如何动态地使用路径。例如,我使用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和必要的。无论如何感谢
答
使用中间件是不可能的。当请求到达时,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")
})
*/
参考:Building a service API Part 4
还是要谢谢你,给我留下了评论,如果有什么东西错用这种方法:d