JSON-Server 是一个零代码的 REST API 模拟工具,它可以在不到 30 秒的时间内为你创建一个完整的假 REST API。它非常适合前端开发者在没有后端支持的情况下进行开发和测试。
首先,确保你的电脑上已经安装了 Node.js。然后打开终端,运行以下命令:
npm install -g json-server
在你的项目目录中创建一个名为 db.json
的文件,这个文件将作为你的数据库。例如:
{
"posts": [
{ "id": 1, "title": "我的第一篇博客", "author": "张三" },
{ "id": 2, "title": "学习心得", "author": "李四" }
],
"comments": [
{ "id": 1, "body": "写得真好!", "postId": 1 },
{ "id": 2, "body": "受益匪浅", "postId": 2 }
]
}
在终端中运行:
json-server --watch db.json
服务器将在 http://localhost:3000
启动。
获取所有文章:
GET http://localhost:3000/posts
获取特定文章:
GET http://localhost:3000/posts/1
POST http://localhost:3000/posts
Content-Type: application/json
{
"title": "新文章",
"author": "王五"
}
PUT http://localhost:3000/posts/1
Content-Type: application/json
{
"title": "修改后的标题",
"author": "张三"
}
DELETE http://localhost:3000/posts/1
获取浏览量大于 100 的文章:
GET http://localhost:3000/posts?views_gt=100
获取第 2 页,每页 5 条数据:
GET http://localhost:3000/posts?_page=2&_per_page=5
按浏览量降序排序:
GET http://localhost:3000/posts?_sort=views&_order=desc
获取文章及其评论:
GET http://localhost:3000/posts?_embed=comments
自定义端口:
json-server --watch db.json --port 3004
添加延迟:
json-server --watch db.json --delay 2000
静态文件服务: 创建 public
文件夹,放入静态文件,它们会被自动提供。
数据没有更新?
db.json
文件有写入权限跨域问题?
--no-cors
参数启动服务器json-server --watch db.json --no-cors
需要更多功能?
JSON-Server 是一个简单但功能强大的工具,它可以帮助你:
现在你可以开始使用 JSON-Server 来加速你的开发流程了!