【问题标题】:Use Express Router to match a route使用 Express Router 匹配路由
【发布时间】:2016-11-29 12:16:16
【问题描述】:

我正在尝试在我的 Express API 中整合大量 route 的使用,我希望有一种方法可以做这样的事情:

const app = express()

const get = {
  fetchByHostname({
    name
  }) {
    return `hey ${name}`
  }
}

const map = {
  '/public/hostname/:hostname': get.fetchByHostname
}

app.use((req, res, next) => {
  const url = req.originalUrl
  const args = { ...req.body, ...req.query }
  const method = map[url] // this won't work
  const result = method(args)
  return res.json({
    data: result
  })
})

我试图避免传递reqres 对象,只在一个地方处理对客户端的响应。是否有 Express/Node/.js 模块或方式来匹配 URL,例如我上面的 map 对象?

【问题讨论】:

    标签: node.js express routing


    【解决方案1】:

    我真的不明白你想要实现什么,但据我所知,你的fectchByHostname({name})应该是fetchByHostname(name),你也许可以返回hey $name。你应该确定你使用的是 ES6,因为有你args。否则,您必须在 es5 args = {body: req.body, query: req.query}; 中定义 as。希望对您有所帮助。

    【讨论】:

    • 我正在使用解构。在args 对象中,将有一个name 的键供我在该方法内部访问。我最终想出了一个解决方案。
    猜你喜欢
    • 2016-09-02
    • 2019-07-20
    • 2021-03-10
    • 2015-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-09
    相关资源
    最近更新 更多