0
点赞
收藏
分享

微信扫一扫

json-server使用

json-server是一个在前端本地运行,可以存储数据的server,作用:模拟接口,操作模拟数据。

github:​​https://github.com/typicode/json-server​​

1、安装:

$ npm install -g json-server
$ json-server -h
json-server [options] <source>

Options:
--config, -c Path to config file [default: "json-server.json"]
--port, -p Set port [default: 3000]
--host, -H Set host [default: "localhost"]
--watch, -w Watch file(s) [boolean]
--routes, -r Path to routes file
--middlewares, -m Paths to middleware files [array]
--static, -s Set static files directory
--read-only, --ro Allow only GET requests [boolean]
--no-cors, --nc Disable Cross-Origin Resource Sharing [boolean]
--no-gzip, --ng Disable GZIP Content-Encoding [boolean]
--snapshots, -S Set snapshots directory [default: "."]
--delay, -d Add delay to responses (ms)
--id, -i Set database id property (e.g. _id) [default: "id"]
--foreignKeySuffix, --fks Set foreign key suffix (e.g. _id as in post_id)
[default: "Id"]
--quiet, -q Suppress log messages from output [boolean]
--help, -h Show help [boolean]
--version, -v Show version number [boolean]

Examples:
json-server db.json
json-server file.js
json-server http://example.com/db.json

https://github.com/typicode/json-server

2、使用:

1)创建json文件:

{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}

2)启动服务:

$ json-server db.json 

\{^_^}/ hi!

Loading db.json
Done

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

Home
http://localhost:3000

 这时,在windows浏览器通过linux的ip+port访问无响应。根据经验,肯定是ip未指定。我们通过如下方式来启动:

$ json-server -H 0.0.0.0 db.json 

\{^_^}/ hi!

Loading db.json
Done

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

Home
http://0.0.0.0:3000

3)访问;

json-server使用_数据

3、高级用法:

可以通过http的get、post、delete等方法实现数据的CRUD,数据会被写入到对应的文件中。

  • 查询
  • GET /list 获取列表
  • GET /list/1 获取id=1的数据
  • 新增
  • POST /list 创建一个项目
  • 修改
  • PUT /list/1 更新一个id为1的数据
  • PATCH /list/1 部分更新id为1的数据
  • 删除
  • DELETE /list/1 删除id为1的数据

 


举报

相关推荐

0 条评论