快速路线中的动态路径

Dynamic path in express routes

我想知道如何在 express 中动态使用路径。例如,我使用 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")
  })
})

在上面的代码中,我只是嵌套了路由。但是没有任何回应。有什么办法可以做到这一点?如有必要,我也想将此方法与数据库一起使用。还是谢谢

使用中间件是不可能的。当请求到来时,expressjs 会先搜索注册的路径。 所以我们来看看为什么该代码也不是 运行。

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

那么如何实现这个目标呢?但是,我们需要在 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