javascript - 在 javascript 中初始化 json-server 时,有没有办法定义 routes.json 文件?
问题描述
如果您想从命令行使用 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 文件。这可能吗?
解决方案
需要使用提供的rewriter
api json-server
。文档中的示例:
// Add this before server.use(router)
server.use(jsonServer.rewriter({
'/api/*': '/$1',
'/blog/:resource/:id/show': '/:resource/:id'
}))