一个在前端本地运行,可以存储json数据的server。
基于node环境,可以指定一个 json 文件作为 API 的数据源。
node
环境json-server
npm install -g json-server
db.json
文件。json-server --watch db.json
json-server
把 db.json
根节点的每一个 key
,当作一个 router
。我们可以根据这个规则来编写测试。http://localhost:3000
,效果如下json-server
默认端口为 3000
,可以根据需要自定义端口号。json-server --watch db.json --port 3006
启动服务
都要执行相关命令,可以在 db.json
同级文件夹新建一个 package.json
文件,然后把以下配置信息放在里面就可以啦。{"scripts": {"mock": "json-server db.json --port 3006"}
}
npm run mock
db.json
文件中{"subject": [{"id": 1,"name": "JAVA","price": 888 },{"id": 2,"name": "GO","price": 2088},{"id": 3,"name": "VUE","price": 288}]
}
url
后面拼接 id
值http://localhost:3006/subject/3
对象
{id: 3,name: "VUE",price: 288
}
GET
的传参方式,拼接需要查询参数http://localhost:3006/subject?id=3
数组
[{id: 3,name: "VUE",price: 288}
]
_page
:页码_limit
:每页显示数量,如果没有指定,默认每页10条数据。http://localhost:3006/subject?_page=1&_limit=2
_sort
:排序字段_order
:排序方式【asc | desc】,默认asc
http://localhost:3006/subject?_sort=id&_order=desc
slice
方式,通过参数 _start
指定开始位置,_end
指定结束位置下标
方式截取_limit
指定开始位置算起,往后取n个数据。http://localhost:3006/subject?_start=3&_end=6http://localhost:3006/subject?_start=3&_limit=6
_gte
: 大于等于_lte
: 小于等于_ne
: 不等于_like
: 模糊查询http://localhost:3006/subject?id_gte=2&_lte=5http://localhost:3006/subject?name_like=V
json
文件,例 json_server_config.json
public
目录,存放静态资源。{"port": 3006,"watch": true,"static": "./public","read-only": false,"on-cors": true,"no-gzip": false
}
package.json
文件中启动命令{"name": "my-json-server","version": "1.0.0","description": "","main": "index.js","scripts": {"mock1": "json-server db.json --port 3006","mock": "json-server --c json_server_config.json db.json"},"keywords": [],"author": "","license": "ISC"
}
public
目录。http://localhost:3006/image/test.png
上一篇:元宇宙营销面临的三大挑战
下一篇:Linux系统之部署个人导航页