使用json-server与Mockjs搭建模拟服务

为什么使用

在项目开发中,常常需要边写前端页面边写后端接口,但是后端接口服务往往是滞后于前端开发的,或者是不能及时提供的。出于前端开发的迅速和便捷去考虑,我们可以根据后端接口数据结构去模拟(mock)数据从而实现前端的独立开发。
JsonServer 主要的作用就是搭建本地的数据接口,创建json文件,便于调试调用
Mockjs 主要的作用就是生成随机数据,支持生成随机的文本、数字、布尔值、日期、邮箱、链接、图片、颜色等

如何使用

以下操作需要node.js环境

1.创建文件夹

选择自己喜欢的位置创建一个文件夹,比如E:/mock

2.安装json-server

进入E:/mock

npm install json-server -g

安装完执行 json-server -h,若安装成功则会显示选项

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]

3.使用json-server
  • 创建json文件,如db.json,文件内容如下
{
    "posts": [
        {
            "id": 1,
            "title": "json-server",
            "author": "typicode"
        }
    ],
    "comments": [
        {
            "id": 1,
            "body": "some comment",
            "postId": 1
        }
    ],
    "profile": {
        "name": "typicode"
    }
}
  • 启动json-server,cmd执行
json-server --watch db.json

看到如下内容

 
1574216715(1).jpg

则运行成功,直接访问图中显示的三个地址可得结果,如
 
1574216903(1).jpg

至此,简单的json-server服务已经搭建成功了,后续如果有更多需求,如跨域、参数查询、路由这些,请参考json-server的github

 

4.安装Mockjs

进入E:/mock

npm install mockjs --save
5.使用Mockjs
  • 创建js文件,如news.js,文件内容如下
let Mock=require('mockjs');
let Random=Mock.Random;

module.exports=()=>{
    let data={
        news:[]
    };

    let images=[1,2,3].map(x=>Random.image('120x60',Random.color(),Random.word(2,6)));

    for(let i=1;i<=100;i++){
        let content=Random.cparagraph(0,10);

        data.news.push({
            id:i,
            title:Random.cword(8,20),
            desc:content.substr(0,40),
            tag:Random.cword(2,6),
            views:Random.integer(100,5000),
            images:images.slice(0,Random.integer(1,3))
        })
    }
    return data
}
  • 启动json-server,cmd执行
json-server --watch news.js

访问结果(部分)


 
 

完成了以上的搭建与验证过程后,你就可以开始使用json-server与Mockjs来继续构建模拟服务器了,来满足自己的各种需要

Tips:

1、也可以使用json-server db.json ,使用“json-server --watch db.json”命令可以实时监测db.json的变化;如果没有 -- watch 命令,即使db.json已经发生了改变,重新发请求,仍然会返回原先的mock data,返回状态码304,认为没有变化。

2、同时,我们可以发送 POST、PUT、PATCH和DELETE请求,相应的结果会通过lowdb自动保存到db.json。关于POST、PUT等相关请求的发送。

3、我们的request body应该是一个json对象,比如{"name":"Lynn"};

4、POST、PUT、PATCH请求头中要包含Content-Type: application/json;

5、id的值是自动生成且不易变的。PUT请求和PATCH请求中自带的id会被忽略。

 

posted on 2020-06-24 19:09  ranyonsue  阅读(2967)  评论(3编辑  收藏  举报

导航