json-server的一些使用

在使用jsonserver模拟接口的时候。

假如写这样的数据:

// db.json
{
"posts": [
{ "id": 1, "name": "json" }
],
"comments": [
{ "id": 2, "name": "server" }
]

}
访问的接口是:

http://localhost:3000/posts
http://localhost:3000/comments

但是,很多时候,这种单一的路由接口并不能满足我们的需求,大多数时候,我们需要的api接口可能是"http://localhost:3000/api/posts ", 或者我们想用的接口并不是3000,而是8080。这就需要一些自定义配置。

首先,我们需要对路由进行简单的自定义配置。

自定义路由——route.json

在同一个文件夹下建一个route.josn的文件

文件内容是:{ "/api/*": "/$1" // /api/posts => /posts }

上面route.json的意思就是,当调用/api/posts时,重定向到/posts

命令行中输入如下命令即可实现简单的自定义路由, 路由文件通过–routes 参数来指定:

json-server --routes route.json db.json

猜你喜欢

转载自www.cnblogs.com/archerhao/p/10152625.html