Json-Server 简单使用

是什么?

用于模拟服务端接口数据,可以根据json数据建立一个完整的web服务。一般用在前后端分离后,前端人员可以不依赖API开发,而在本地搭建一个JSON服务,自己产生测试数据。

怎么安装?

依赖nodejs ,需要提前安装好nodejs。

# 安装
npm install -g json-server

# 查看版本
C:\Users\hp>json-server -v
0.17.1

# 创建文件夹
D:\workspace\server\jsonServer

# 创建db.json 文件并赋值如下json格式内容
db.json
{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment", "postId": 1 }
  ],
  "profile": { "name": "typicode" }
}


# 启动json-server 接口服务器
# 指定端口
# json-server --watch db.json --port 5222
D:\workspace\server\jsonServer>json-server -w db.json

  \{^_^}/ hi!

  Loading db.json
  Done

  Resources
  http://localhost:3000/posts
  http://localhost:3000/comments
  http://localhost:3000/profile

  Home
  http://localhost:3000

  Type s + enter at any time to create a snapshot of the database
  Watching...

通过配置信息配置静态资源

json_server_config.json

{
  "port": 3000,            
  "watch": true,           
  "static": "./public",
  "read-only": false, 
  "no-cors": false, 
  "no-gzip": false
}

package.json

{
    "scripts": {
        "mock": "json-server -c json_server_config.json db.json"
    }
}

 

D:\workspace\server\jsonServer>npm run mock

 

怎么用?

在浏览器中输入地址:http://localhost:+端口号/接口名称,即可查看数据

查看静态资源

 http://localhost:3000/img/tp.png

新增数据

POST: http://localhost:3000/posts
{ "id": 3, "title": "json-server-3", "author": "typicode-3" }

修改数据

删除数据

DELETE:http://localhost:3000/posts/3  

tips:还有查询过滤、排序等等用法可自行查阅资料,使用不多

 

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

每天都要有成长

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值