是什么?
用于模拟服务端接口数据,可以根据json数据建立一个完整的web服务。一般用在前后端分离后,前端人员可以不依赖API开发,而在本地搭建一个JSON服务,自己产生测试数据。
怎么安装?
依赖nodejs ,需要提前安装好nodejs。
# 安装
npm install -g json-server
# 查看版本
C:\Users\hp>json-server -v
0.17.1
# 创建文件夹
D:\workspace\server\jsonServer
# 创建db.json 文件并赋值如下json格式内容
db.json
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": { "name": "typicode" }
}
# 启动json-server 接口服务器
# 指定端口
# json-server --watch db.json --port 5222
D:\workspace\server\jsonServer>json-server -w db.json
\{^_^}/ hi!
Loading db.json
Done
Resources
http://localhost:3000/posts
http://localhost:3000/comments
http://localhost:3000/profile
Home
http://localhost:3000
Type s + enter at any time to create a snapshot of the database
Watching...
通过配置信息配置静态资源
json_server_config.json
{
"port": 3000,
"watch": true,
"static": "./public",
"read-only": false,
"no-cors": false,
"no-gzip": false
}
package.json
{
"scripts": {
"mock": "json-server -c json_server_config.json db.json"
}
}
D:\workspace\server\jsonServer>npm run mock
怎么用?
在浏览器中输入地址:http://localhost:+端口号/接口名称,即可查看数据
查看静态资源
http://localhost:3000/img/tp.png
新增数据
POST: http://localhost:3000/posts
{ "id": 3, "title": "json-server-3", "author": "typicode-3" }
修改数据
删除数据
DELETE:http://localhost:3000/posts/3
tips:还有查询过滤、排序等等用法可自行查阅资料,使用不多