json-server 的基本使用
官方链接:https://www.npmjs.com/package/json-server#add-custom-routes
简述#
可以根据json文件快速在本地启动服务提供API接口
安装#
npm install -g json-server
基本使用#
- 创建
db.json
文件
{
"students": [
{
"id": 1,
"name": "孙悟空",
"age": 20
},
{
"id": 2,
"name": "猪八戒",
"age": 30
},
{
"id": 5,
"name": "沙和尚",
"age": 16
},
{
"id":4,
"name":"白骨精",
"age":18
},
{
"id":3,
"name":"捣乱的",
"age":16
}
],
"address": [
"北京路1号",
"上海路2号",
"广州路3号"
]
}
- 启动json-server服务
json-server --watch db.json
- 发送请求
获取students
中的所有数据
http://localhost:3000/students
获取指定数据#
获取students
中id为3的数据
http://localhost:3000/students/3
获取students
中name为白骨精并且age为18的数据
http://localhost:3000/students?name=白骨精&age=18
分页#
- 使用
_limit
来限制默认返回的条数,默认会返回所有; - 使用
_page
指定页数
需求1:返回students中2条数据
http://localhost:3000/students?_limit=2
需求2:返回students中第二页的数据
http://localhost:3000/students?_limit=2&_page=2
排序#
- 默认情况下根据升序排列;
- 使用
_sort
指定什么进行排序 - 使用
_order
指定是升序(asc)还是降序(desc)。
需求:根据students中的age进行降序
http://localhost:3000/students?_order=desc&_sort=age
需求:根据students中age降序、id的升序
http://localhost:3000/students?_order=desc,asc&_sort=age,id
获取数组中指定范围的数据#
类似数组中的Array.slice
- 使用
_start
指定数组的开始索引,包括此索引 - 使用
_end
指定数组的结束索引,不包括此索引
需求:获取students中索引为1到4(不包含4)的数据
http://localhost:3000/students?_start=1&_end=4
需求:获取students中索引为1,长度为2的数据
http://localhost:3000/students?_start=1&_limit=2
比较#
- 大于使用
xx_gte
greate than equal - 小于使用
xx_lte
less than equal - 不等于使用
xx_ne
not equal - 正则匹配使用
xx_like
需求:获取students中age大于等于18的数据
http://localhost:3000/students?age_gte=18
需求:获取students中name包含了"和"的数据
http://localhost:3000/students?name_like=和
全文检索#
- 大概的意思是只要有包含就匹配把
需求:获取students中age包含16的数据
http://localhost:3000/students?q=16
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)