jsonserver(mock和json server)

[img]

简介:

JSON Server 是一个基于 Node.js 和 JSON 文件的完整的后端 API 模拟工具,能够快速帮你创建一个可用于开发、测试和学习的 RESTful API,特别针对前端开发者。在开发中,我们常常会遇到后端 API 尚未完成或者联调的问题,借助 JSON Server 可以快速搭建一个本地的 RESTful API 服务。

多级标题:

一、安装 JSON Server

二、创建一个简单的 API

三、高级示例——嵌套资源

四、使用 JSON Server 的快速方法

内容详细说明:

一、安装 JSON Server

首先,你需要使用 node.js 自带的包管理器 npm 安装 json-server:

```

npm install -g json-server

```

二、创建一个简单的 API

创建一个 JSON 文件,例如 db.json,示例内容如下:

```

"posts": [

{

"id": 1,

"title": "json-server",

"author": "John Doe"

},

{

"id": 2,

"title": "another post",

"author": "Jane Doe"

}

],

"comments": [

{

"id": 1,

"body": "some comment",

"postId": 1

}

],

"profile": {

"name": "typicode"

}

```

运行以下命令,启动 JSON Server,默认会监听本地 3000 端口:

```

json-server --watch db.json

```

此时,你可以通过访问 http://localhost:3000/posts 来获取 posts 资源的全部内容。

三、高级示例——嵌套资源

在实际开发中,我们可能会需要访问嵌套的资源,例如返回某篇文章的所有评论信息。此时,只需在 db.json 文件中添加嵌套的数据即可,例如:

```

"posts": [

{

"id": 1,

"title": "json-server",

"author": "John Doe",

"comments": [

{

"id": 1,

"body": "some comment"

}

]

}

]

```

启动 JSON Server:

```

json-server --watch db.json

```

你可以通过访问以下 URL 来获取 posts 的全部内容,即此时已经添加了comments 资源:

```

http://localhost:3000/posts

```

你也可以通过 tags 资源下 category 资源下 articles 资源中的所有文章,例如:

```

http://localhost:3000/tags/1/category/3/articles

```

四、使用 JSON Server 的快速方法

如果你不想手动编写一个 JSON 文件来模拟一个 API 服务,JSON Server 还提供了快速创建一个模拟 API 服务的方法,只需运行以下命令:

```

json-server https://jsonplaceholder.typicode.com/db

```

这样,你就可以通过访问 http://localhost:3000/users 来获取 jsonplaceholder 的 users 资源了。

最后,如果想了解更多关于 JSON Server 的细节配置,可以参考官方文档:https://github.com/typicode/json-server。

标签列表