【问题标题】:Is there a way to define a routes.json file when initializing a json-server in javascript?在 javascript 中初始化 json-server 时,有没有办法定义 routes.json 文件?
【发布时间】:2021-04-19 00:14:28
【问题描述】:

如果您想使用 routes.json 文件从命令行自定义 json-server 路由,您可以使用 --routes 选项执行此操作,如下所示:

json-server --watch db/db.json --routes db/routes.json --port 9001

但是,如果您从 javascript 文件启动 json-server,我在任何地方都看不到类似的选项。我正在寻找这样的东西:

const server = jsonServer.create();
const router = jsonServer.router('db.json')
server.use(router)

// This part is what I am looking for
const customRouter = jsonServer.customRouter('routes.json')
server.use(customRouter)

server.listen(3000, () => {
  console.log('JSON Server is running')
})

我知道我们可以在 javascript 中进行显式自定义路由,但这很冗长,我更愿意只引用 routes.json 文件。这可能吗?

【问题讨论】:

    标签: javascript json-server


    【解决方案1】:

    您需要使用json-server 提供的rewriter api。 来自documentation 的示例:

    // Add this before server.use(router)
    server.use(jsonServer.rewriter({
      '/api/*': '/$1',
      '/blog/:resource/:id/show': '/:resource/:id'
    }))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-11-13
      • 1970-01-01
      • 2021-06-09
      • 2021-02-26
      • 2018-07-23
      • 2021-09-18
      • 1970-01-01
      相关资源
      最近更新 更多