json-server使用方法
下面是一个关于 json-server
的详细使用指南,包括安装、配置以及一些基本操作的示例。
1. 安装 json-server
首先确保你已经安装了 Node.js 和 npm(Node 包管理器)。如果尚未安装,请访问 Node.js 官网下载并安装适合你的版本。
接下来,在命令行中全局安装 json-server
:
npm install -g json-server
2. 创建数据库文件
创建一个 JSON 文件作为数据源。例如,我们创建一个名为 db.json
的文件,并添加一些初始数据:
{
"posts": [
{ "id": 1, "title": "json-server", "author": "typicode" }
],
"comments": [
{ "id": 1, "body": "some comment", "postId": 1 }
],
"profile": {
"name": "typicode"
}
}
3. 启动服务器
在项目根目录下运行以下命令启动服务器:
json-server --watch db.json
默认情况下,服务器会在 http://localhost:3000
上监听请求。
4. RESTful API 示例
假设我们的 db.json
如上所述,以下是与之交互的一些 RESTful 请求示例:
查询所有 posts
GET /posts
返回:
[
{ "id": 1, "title": "json-server", "author": "typicode" }
]
获取特定 post
GET /posts/1
返回:
{ "id": 1, "title": "json-server", "author": "typicode" }
添加新的 post
POST /posts
Content-Type: application/json
{
"title": "New Post",
"author": "Someone Else"
}
返回新创建的资源:
{ "id": 2, "title": "New Post", "author": "Someone Else" }
更新 post
PUT /posts/1
Content-Type: application/json
{
"title": "Updated Title",
"author": "Updated Author"
}
返回更新后的资源:
{ "id": 1, "title": "Updated Title", "author": "Updated Author" }
删除 post
DELETE /posts/1
成功后返回 HTTP 状态码 200 OK
。
5. 高级功能
- 分页:可以通过
_page
和_limit
参数来实现分页查询。 - 排序:通过
_sort
和_order
参数来对结果进行排序。 - 过滤:通过查询参数来进行简单的过滤,比如
/posts?title=json-server
。 - 嵌套资源:支持关联查询,如
/posts?_embed=comments
。
6. 使用中间件
你可以使用自定义中间件来扩展 json-server
的功能。例如,添加日志记录中间件:
// middlewares.js
module.exports = (req, res, next) => {
console.log('Request Type:', req.method, req.url);
next();
};
然后在启动时指定中间件:
json-server --watch db.json --middlewares ./middlewares.js
7. 自定义端口
如果你不想使用默认的 3000
端口,可以通过 --port
参数指定不同的端口号:
json-server --watch db.json --port 8080
这样,你的服务器就会在 http://localhost:8080
上运行。