json-server使用 - 图1

在他的帮助下可以在很短的时间内搭建一个Rest API, 然后就可以让前端在不依赖后端的情况下进行开发啦

全局安装json-server

  1. npm install -g json-server

创建项目并初始化

  1. mkdir jsonServer
  2. cd jsonServer
  3. yarn init -y

新建初始化数据

根目录下新建db.jsson(默认命名不可修改)

db.json数据初始值

  1. {
  2. "posts": [
  3. {
  4. "id": 1,
  5. "title": "json-server",
  6. "author": "typicode"
  7. }
  8. ],
  9. "comments": [
  10. {
  11. "id": 1,
  12. "body": "some comment",
  13. "postid": 1
  14. }
  15. ],
  16. "profile": {
  17. "name": "typicode"
  18. }
  19. }

启动json-server服务

  1. json-server watch db.json

访问localhost:3000即可访问

常见访问接口

get (获取数据)

  1. localhost:3000/posts //获取posts列表数据
  2. localhost:3000/posts/1 //获取posts列表数据中id等于1的数据

post (添加数据)

  1. $.ajax({
  2. type: "post",
  3. url: "http://127.0.0.1:3000/posts",
  4. dataType: "json",
  5. data: {
  6. "title": "888",
  7. "author": "8555"
  8. },
  9. success: function (data) {
  10. },
  11. error: function (e) {
  12. }
  13. });

db.json里面的数据自动变化

  1. "posts": [
  2. {
  3. "id": 1,
  4. "title": "json-server",
  5. "author": "typicode"
  6. },
  7. {
  8. "title": "888",
  9. "author": "8555",
  10. "id": 2
  11. }
  12. ]

put 修改数组对应id内容

  1. $.ajax({
  2. type: "PUT",
  3. url: "http://127.0.0.1:3000/posts/3",
  4. dataType: "json",
  5. data: {
  6. "title": "修改文件",
  7. "author": "刘鹏"
  8. },
  9. success: function (data) {
  10. },
  11. error: function (e) {
  12. }
  13. });

delect 删除数组对应id的内容

  1. $.ajax({
  2. type: 'DELETE',
  3. url: "http://127.0.0.1:3000/posts/1",
  4. dataType: "json",
  5. success: function (data) {
  6. },
  7. error: function (e) {
  8. }
  9. });

筛选条件实现(get)

  1. http://localhost:3000/posts?title=json-server&author=typicode

执行结果为

  1. [
  2. {
  3. title: "json-server",
  4. author: "typicode",
  5. id: 1
  6. }
  7. ]

分页数据实现 (get)

  1. http://localhost:3000/posts?_page=1&_limit=2
  2. // page 页数 limit每页条数

数据排序实现(get)

  1. http://localhost:3000/posts?_sort=id&_order=desc
  2. http://localhost:3000/posts/1/comments?_sort=votes&_order=asc

数据筛选的实现(get)

  1. http://localhost:3000/posts?_start=2&_end=4
  2. http://localhost:3000/posts/1/comments?_start=0&_limit=5

标题检索的实现(get)

  1. http://localhost:3000/posts?q=internet
  2. //搜索标题中含有Internet的数据