json-server如何使用
时间: 2023-12-29 07:03:27 浏览: 30
JSON Server 是一个快速的 Mock 服务器,可以快速地搭建一个本地的 REST API 。下面是 JSON Server 的使用方法:
1. 安装 JSON Server
```bash
npm install -g json-server
```
2. 创建一个 JSON 文件
例如,我们创建一个名为 `db.json` 的 JSON 文件,内容如下:
```json
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" },
{ "id": 2, "title": "mock-server", "author": "John Doe" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 },
{ "id": 2, "body": "another comment", "postId": 2 }
]
}
```
3. 启动 JSON Server
打开命令行界面,进入到包含 `db.json` 文件的目录下,执行以下命令:
```bash
json-server --watch db.json
```
这样就启动了一个 JSON Server,默认监听在 `http://localhost:3000` 上。
4. 访问 API
现在,我们就可以通过 `http://localhost:3000/posts` 和 `http://localhost:3000/comments` 访问我们刚刚创建的 REST API 了。
例如,我们可以访问 `http://localhost:3000/posts/1` 来获取 ID 为 1 的 post 的详细信息。
同时,JSON Server 还支持各种高级功能,例如关联,过滤,排序等等。详细的使用方法可以参考官方文档:https://github.com/typicode/json-server