Json-server搭建前端虚拟REST API服务

唠唠嗑、

为什么要来详细介绍一下json-server呢?因为我们前端开发人员在开发后台管理类项目的过程中打交道最多还是API联调,然后数据渲染页面,或者动态数据绑定。

但是有个很矛盾的问题就是,很多时候前后端是一起开发的,有可能后端的进度赶不上前端的进度。一般情况下的解决办法就是在前端应用里面写死数据模拟,在缺少了请求的一个过程后,在更新数据,删除数据等一些页面切换复杂交互的场景下,死数据还需要vuex或redux的支持。

在前端安装json-server依赖,可以很好的解决这些问题,在写前端页面逻辑的时候可以直接请求交互,添加、更新、删除数据可以直接修改本地json文件里面的数据。就不需要在全局定义变量保存数据。且可以直接跨域请求,不需要同源请求才能联调。

一、安装

1.npm安装 (建议cnpm安装)
   npm install -g json-server 
2.yarn安装
   yarn  global add json-server

安装成功后打印出:

C:\Users\92809>yarn global add json-server
yarn global v1.10.1
[1/4] Resolving packages...
[2/4] Fetching packages...
[3/4] Linking dependencies...
[4/4] Building fresh packages...

success Installed "[email protected]" with binaries:
      - json-server

二、创建json数据库数据表

1.创建一个自定义dbname.json/ dbname.js文件
2.dbname文件内文件格式保持json风格
3.Json风格如下:

{
  "posts": [
    { "id": 1, "title": "json-server", "author": "typicode" }
  ],
  "comments": [
    { "id": 1, "body": "some comment1", "author": { "name": "typicode1", "age": 10 },"postId": 1 },
    { "id": 2, "body": "some comment2", "author": { "name": "typicode2", "age": 12 },"postId": 2 },
    { "id": 3, "body": "some comment3", "author": { "name": "typicode3", "age": 15 },"postId": 3 }
  ],
  "profile": { "name": "typicode" }
}

4.Js风格如下:

module.exports = function() {
  return {//...}
};


三、打开json-server服务

(1)原生态打开

D:\me\json-server\jserver-one>json-server --w onedb.json

  \{^_^}/ hi!

  Loading onedb.json
  Done

  Resources
  http://localhost:3000/news
  http://localhost:3000/comments

  Home
  http://localhost:3000

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

(2)打开远程json数据库文件

$ json-server http://example.com/file.json
$ json-server http://jsonplaceholder.typicode.com/db

(3)设置服务端口号

json-server --watch db.json --port 3004

(4)yarn / npm打开

  2-1.  yarn init / npm init
  2-2. 在初始化的package.json文件中新增:
 

 "scripts": {
     "server": "json-server onedb.json --port 3003"
    }


  2-3. 运行:

npm run server / yarn run server /. yarn server

(4)作为服务器加载本地静态网页

md asset
cd asset
echo asset.html > asset.html
json-server onedb.json --port 3006 --static asset [ 资源目录名 ]

访问:http://localhost:3006/asset.html (OK)

注:如果启动时没有配置目录 -> json-server onedb.json --port 3006 

4-1. 如果有设置public目录,http://localhost:3006/访问的是public下的index.html文件
4-2. 如果没有public目录或index,html文件则显示 {} 


四、json-server提供的请求方式

简述:Get请求主要用于获取数据,POST请求用于新增数据,PUT请求用于修改替换数据,PATCH表示部分替换数据,OPTIONS用于获取服务器支持的HTTP请求方法及其他请求功能选项(GET、POST、PUT、DELETE、PATCH、OPTIONS)

注:POST\PUT\PATCH请求需要设置请求头Content-type: application/json

1.基础请求方式

GET    /posts
GET    /posts/:id
POST   /posts
PUT    /posts/:id
PATCH  /posts/:id
DELETE /posts/:id

2.获取json数据库中所有数据

GET /db

3.带参数查找请求方式

GET /posts?title=json-server&author=typicode
GET /posts?id=1&postid=2
GET /comments?author.name=typicode1  * 使用.访问下级属性值

4.页面分页链接请求(first、last、prev、next)

GET /posts?_page=7
GET /posts?_page=7&_limit=20

5.升降序排列请求

GET /users?_sort=id&_order=asc
GET /users?_sort=name&_order=asc

多条件升降序: GET /posts?_sort=user,views&_order=desc,asc

6.范围查询数据

GET /users?_start=2&_end=20 (类似于substring)
GET /users?_start=2&_limit=3    (类似于substr)

7.根据文字模糊匹配查询数据

GET /users?q=情感

五、自定义路由配置

1.新建一个routes.json文件:echo {} > routes.json
2.向文件中写入:

{
  "/api/*": "/$1",
  "/:resource/:id/show": "/:resource/:id",
  "/books/:name": "/books?name=:name",
  "/articles\\?id=:id": "/books/:id",
  "/articles/:id": "/books/:id"
}

3.启动服务:json-server onedb.js --routes routes.json

打印: 

 \{^_^}/ hi!

  Loading onedb.js
  Loading routes.json
  Done

  Resources
  http://localhost:3000/users
  http://localhost:3000/books

  Other routes
  /api/* -> /$1
  /:resource/:id/show -> /:resource/:id
  /books/:name -> /books?name=:name
  /articles\?id=:id -> /books/:id
  /articles/:id -> /books/:id

  Home
  http://localhost:3000

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

4.测试ap接口

  GET /api/users  等价于 GET /users
  GET /users/1/show 等价于 GET /users/1
  GET /books/意林 等价于 GET/books?name=意林
  GET /articles?id=3 等价于 GET /books/3

六、Node模块中引入使用方法

1.新建server.js文件:echo server > server.js
2.依赖安装json-server、express : 

cnpm install express --save-dev
cnpm install json-server --save-dev
或者:
yarn add express  --dev
yarn add json-server --dev 


开启服务: node server.js

2-1.使用 express开启服务:

const app = require('express')();

app.get('/',(req,res)=>{
    res.send({'name':'哆啦A梦'});
});

var server = app.listen(3008,()=>{
    var host = server.address().address;
    var port = server.address().port; 
    console.log('example app listening at http://%s:%s',host,port);
});

2-2. 使用json-server开启服务

const jsonServer = require('json-server')
const server = jsonServer.create()
const router = jsonServer.router('onedb.json')
const middlewares = jsonServer.defaults()

server.use(middlewares)
server.use(router)
server.listen(3009, () => {
  console.log('JSON Server is running at port 3009.')
})

七、json-server在node中的进阶使用

1.自定义路由配置

(1)在上述json-server.js文件中新增:

//在JSON Server router之前添加自定义路由
server.get('/echo', (req, res) => {
  res.jsonp(req.query)
})

//你需要使用一个body-parser来处理POST,PUT和PATCH
//你可以使用JSON Server使用的那个
server.use(jsonServer.bodyParser)
server.use((req, res, next) => {
  if (req.method === 'POST') {
    req.body.createdAt = Date.now()
  }
  // 继续json-server路由
  next()
})

(2)启动服务 node json-srevr.js
(3)测试自定义接口:

  请求: GET /echo?id=2&pid=3&page=20
  响应: { "id": "2", "pid": "3", "page": "20" }


2.访问权限控制

server.use((req, res, next) => {
 if (isAuthorized(req)) { // 在这儿添加你的权限逻辑
   next() // 继续json-server路由
 } else {
   res.sendStatus(401)
 }
})

3.过滤本地json数据,格式化后响应给请求

// In this example, returned resources will be wrapped in a body property
router.render = (req, res) => {
  res.jsonp({
    body: res.locals.data  // res.locals.data 代表重onedb.json中查询到到的内容
  })
}

4.自定义返回状态码

// In this example we simulate a server side error response
router.render = (req, res) => {
  res.status(500).jsonp({
    body: res.locals.data,
    error: "error message here"
  })
}


5.添加路由重定向规则 

// Add this before server.use(router)
server.use(jsonServer.rewriter({
  '/api/*': '/$1',
  '/blog/:resource/:id/show': '/:resource/:id'
}))

测试:GET /api/comments 等价于 GET /comments

6.创建子路由对象

server.use('/api', router)


八、再唠唠

  在Angular的单元测试中接触到了json-server,然后觉得这个虚拟前端服务使用起来非常顺手。然后花了一整天的时间,完完整整的把json-srever的相关知识点和使用方法捋了一遍,确实是个很好的服务,但是和node结合起来的话,有感觉有些别扭;有可能是我用express用习惯了,但是怎么说呢,功能确实很强大,但是后面些好多和express结合起来开发的时候就有点感觉小重的感觉。违背了轻、快、巧的初衷,不过这个也是看个人喜好,个人建议还是和npm或者yarn结合起来用,一行命令搞定,要清爽的多 哈哈~~
 

九、再啰嗦几句、哈哈

好的项目需要我们大家的一起的支持,多多点赞,这样作者大大才能提供给我们更多更优质的可以学习和使用的源代码,github源码项目地址:https://github.com/typicode/json-server#mounting-json-server-on-another-endpoint-example

猜你喜欢

转载自blog.csdn.net/WU5229485/article/details/83028007