前端必备技能server-json

json-server 是一个快速构建 REST API 的工具,可以轻松地将一个 JSON 文件转换为一个简单的 API。以下是使用 json-server 构建 JSON API 的步骤:

步骤 1: 安装 json-server

首先,你需要安装 json-server。你可以全局安装它,这样你可以在任何地方使用它:

npm install -g json-server

步骤 2: 创建一个 JSON 文件

接下来,创建一个 JSON 文件作为你的数据源。假设我们创建一个名为 db.json 的文件,并添加一些初始数据:

{
  "posts": [
    { "id": 1, "title": "你好js", "author": "ivan" },
    { "id": 2, "title": "学习json-server", "author": "小川" }
  ],
  "comments": [
    { "id": 1, "postId": 1, "body": "Great post!" },
    { "id": 2, "postId": 1, "body": "Thanks for sharing!" }
  ],
  "profile": { "name": "John Doe" }
}

步骤 3: 启动 JSON 服务器

使用以下命令启动 json-server 并指定数据文件:

json-server --watch db.json

默认情况下,json-server 将在 http://localhost:3000 启动服务器。

使用 API

现在,你可以访问以下端点来操作数据:

获取所有 posts:
GET http://localhost:3000/posts

获取特定的 post:
GET http://localhost:3000/posts/1

添加新的 post:
POST http://localhost:3000/posts
Content-Type: application/json

{
  "title": "New Post",
  "author": "John Smith"
}

更新 post:
PUT http://localhost:3000/posts/1
Content-Type: application/json

{
  "title": "Updated Post",
  "author": "John Doe"
}


删除 post:
DELETE http://localhost:3000/posts/1


自定义路由

你还可以创建一个 routes.json 文件来自定义路由。例如:

{
  "/api/posts/": "/posts",
  "/api/comments/": "/comments"
}

启动服务器时指定路由文件:

json-server --watch db.json --routes routes.json

这样你就可以通过 /api/posts/api/comments 访问数据。

json-server 是一个非常方便的工具,可以快速设置一个 REST API 进行开发和测试。只需几行命令和一个 JSON 文件,就能让你在几分钟内创建出一个功能完备的 API。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值