javascript - 快速 route 的动态路径

标签 javascript node.js express url url-routing

我想知道如何在 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

关于javascript - 快速 route 的动态路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46754800/

相关文章:

node.js - 如何在 Express.js 中读取并生成 pdf?

node.js - Node.js Express 中的异步代码

amazon-web-services - AWS 上的无服务器 Express/jade 网站

javascript - 谷歌地图拖动ajax不工作

javascript - 可点击的 html 表格单元格

javascript - Angular.js : How do I make my radio button selected on load?

javascript - IE8 显示位置 .css 错误,但 Chrome 没问题

node.js - 错误: getaddrinfo ENOTFOUND while making get request to localhost, Nodejs

node.js - 阻止 Mongoose 为子文档数组项创建 _id 属性

javascript - Nightmarejs 同一测试中的多个页面