json-server和fakerj模拟REST API mockjs


 

关于什么是RESTful API:
《RESTful API 设计指南》—— 阮一峰
http://www.ruanyifeng.com/blo...

JSON-Server

安装JSON-Server

npm install -g json-server //osx系统加'sudo'

新建一个文件夹同时cd它:

mkdir customer-manager && cd customer-manager

新建一个json文件,然后存放一点数据进去:

touch customers.json
{
  "customers": [
    { "id": 1, "first_name": "John", "last_name": "Smith",  "phone": "219-839-2819" }
  ]
}

 

开启json-server功能

所有你要做的事情只是让json-server指向这个customers.json就ok啦!

json-server customers.js

然后出现这个提示就ok啦!

另外,JSON-Server很酷的一点就是支持各种GET/POST/PUT/DELETE的请求。
看几个例子:

//GET
fetch('http://localhost:3000/tasks/')
  .then(function(response) {
    return response.json()
  }).then(function(json) {
    console.log('parsed json: ', json)
  }).catch(function(ex) {
    console.log('parsing failed: ', ex)
  });


//POST
fetch('http://localhost:3000/tasks/', {
  method: 'post',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
       "title":   "Add a blogpost about Angular2",
       "dueDate": "2015-05-23T18:25:43.511Z",
       "done": false
   })
}).then(function(response) {
      return response.json()
    }).then(function(json) {
      console.log('parsed json: ', json)
    }).catch(function(ex) {
      console.log('parsing failed: ', ex)
    });
    
    
//PUT
fetch('http://localhost:3000/tasks/1', { //在url后面指定下id就好
  method: 'put',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
       "done": true
   })
}).then(function(response) {
      return response.json()
    }).then(function(json) {
      console.log('parsed json: ', json)
    }).catch(function(ex) {
      console.log('parsing failed: ', ex)
    });
    
    
//DELETE
fetch('http://localhost:3000/tasks/1', {
method: 'delete'
}).then(function(response) {
   return response.json()
 }).then(function(json) {
   console.log('parsed json: ', json)
 }).catch(function(ex) {
   console.log('parsing failed: ', ex)
 });

 

JSON-Server基本就是这样啦!接下来介绍另一个神器~

Faker.js

如果要自己瞎编API数据的话也是比较烦恼,用faker.js就可以轻松解决这个问题啦!他可以帮助你自动生成大量fake的json数据,作为后端数据~

安装faker.js

还是使用npm来安装faker.js:

npm install faker

现在我们用javascript生成一个包含50个客户数据的json文件:

//customers.js
var faker = require('faker')

function generateCustomers () {
  var customers = []

  for (var id = 0; id < 50; id++) {
    var firstName = faker.name.firstName()
    var lastName = faker.name.firstName()
    var phoneNumber = faker.phone.phoneNumberFormat()

    customers.push({
      "id": id,
      "first_name": firstName,
      "last_name": lastName,
      "phone": phoneNumber
    })
  }

  return { "customers": customers }
}

 

 // 如果你要用json-server的话,就需要export这个生成fake data的function module.exports = generateCustomers

然后让json-server指向这个js文件:

json-server customers.js

这样你就可以在http://localhost:3000/customers里看到50个客户数据了。
更多faker.js属性可以查看这里:
https://github.com/marak/Fake...

mockjs 

Mock.js 是一款模拟数据生成器,旨在帮助前端攻城师独立于后端进行开发,帮助编写单元测试。提供了以下模拟功能:

  • 根据数据模板生成模拟数据
  • 模拟 Ajax 请求,生成并返回模拟数据
  • 基于 HTML 模板生成模拟数据

github:

https://github.com/nuysoft/Mock

官方网站:

http://mockjs.com/

 开发手册与使用指南:

https://github.com/nuysoft/Mock/wiki/Getting-Started

 

直接上代码:

复制代码
<!DOCTYPE html><html lang="en"><head>
    <meta charset="UTF-8">
    <title>Document</title><script src="http://cdn.bootcss.com/jquery/3.1.1/jquery.min.js"></script><script src="http://mockjs.com/dist/mock.js"></script></head><body><div>
    <h1 id="mockjs">mockjs</h1></div><script type="text/javascript">

    //调用mock方法模拟数据  
  Mock.mock(
        'http://mockjs', {
            "userName" : '@name',     //模拟名称             "age|1-100":100,          //模拟年龄(1-100)             "color"    : "@color",    //模拟色值             "date"     : "@date('yyyy-MM-dd')",  //模拟时间             "url"      : "@url()",     //模拟url             "content"  : "@cparagraph()" //模拟文本
        }     );
   //ajax请求
    $("#mockjs").click(function(){         $.ajax({             url        : "http://mockjs",    //请求的url地址
            dataType   : "json",   //返回格式为json
            async      : true, //请求是否异步,默认为异步,这也是ajax重要特性
            data       : {},    //参数值 
          type       : "GET",   //请求方式
            beforeSend : function() {
                //请求前的处理
            },             success: function(req) {
                //请求成功时处理
                console.log(req);             },             complete: function() {
                //请求完成的处理
            },             error: function() {
                //请求出错处理
            }         });
    });
</script>
</body>
</html>
复制代码

 

CommonJs规范

复制代码
window.Mock = require('mockjs'window.M =window.R = window.Mock.Random;

console.log(R.email())
console.log(M({email:'@email'}))  // 这种@的方式叫"占位符"。它可以用来直接生成各种数据

复制代码

 

Mock.Random 提供的完整方法(占位符)如下:

Type Method
Basic boolean, natural, integer, float, character, string, range, date, time, datetime, now
Image image, dataImage
Color color
Text paragraph, sentence, word, title, cparagraph, csentence, cword, ctitle
Name first, last, name, cfirst, clast, cname
Web url, domain, email, ip, tld
Address area, region
Helper capitalize, upper, lower, pick, shuffle
Miscellaneous guid, id
复制代码
 // 所有@占位符,都是R对象的演变,比如@email就是如下:
        console.log(R.email())        // basic:https://github.com/nuysoft/Mock/wiki/Basic         console.log(M({boolean:'@boolean'}))         console.log(M({natural:'@natural'}))         console.log(M({integer:'@integer'}))         console.log(M({float:'@float'}))         console.log(M({character:'@character'}))         console.log(M({range:'@range'}))        // date:https://github.com/nuysoft/Mock/wiki/Date         console.log(M({date:'@date'}))         console.log(M({time:'@time'}))         console.log(M({datetime:'@datetime'}))         console.log(M({now:'@now'}))        // Image:https://github.com/nuysoft/Mock/wiki/Image         console.log(M({image:"@image()"}))         console.log(M({image:"@image(60x60)"}))         console.log(M({image:"@image(60x60,#000000)"}))         console.log(M({image:"@image('200x100', '#00405d', '#FFF', 'Mock.js')"}))         console.log(M({dataImage:'@dataImage'}))         console.log(M({dataImage:"@dataImage('200x100')"}))         console.log(M({dataImage:"@dataImage('200x100', 'Hello Mock.js!')"}))        // color : https://github.com/nuysoft/Mock/wiki/Color         console.log(M({color:'@color'}))         console.log(M({hex:'@hex'}))         console.log(M({rgb:'@rgb'}))         console.log(M({rgba:'@rgba'}))         console.log(M({hsl:'@hsl'}))        // text : https://github.com/nuysoft/Mock/wiki/Text         console.log(M({paragraph:'@paragraph'}))         console.log(M({sentence:'@sentence'}))         console.log(M({title:'@title'}))         console.log(M({cparagraph:'@cparagraph'}))         console.log(M({csentence:'@csentence'}))         console.log(M({cword:'@cword'}))         console.log(M({ctitle:'@ctitle'}))        // name : https://github.com/nuysoft/Mock/wiki/Name         console.log(M({first:'@first'}))         console.log(M({last:'@last'}))         console.log(M({name:'@name'}))         console.log(M({cfirst:'@cfirst'}))         console.log(M({clast:'@clast'}))         console.log(M({cname:'@cname'}))        // Web : https://github.com/nuysoft/Mock/wiki/Name         console.log(M({url:'@url'}))         console.log(M({domain:'@domain'}))         console.log(M({email:'@email'}))         console.log(M({ip:'@ip'}))         console.log(M({tld:'@tld'}))        // address: https://github.com/nuysoft/Mock/wiki/Name         console.log(M({region:'@region'}))         console.log(M({province:'@province'}))         console.log(M({city:'@city'}))         console.log(M({county:'@county'}))         console.log(M({zip:'@zip'}))        // helper Methods : https://github.com/nuysoft/Mock/wiki/Helper         console.log(M({capitalize:'@capitalize(`hello`)'}))         console.log(M({upper:'@upper(`hello`)'}))         console.log(M({lower:'@lower(`HELLO`)'}))         console.log(M({pick:"@pick(['a', 'e', 'i', 'o', 'u'])"}))         console.log(M({shuffle:"@shuffle(['a', 'e', 'i', 'o', 'u'])"}))        // Miscellaneous: https://github.com/nuysoft/Mock/wiki/Miscellaneous         console.log(M({guid:'@guid'}))         console.log(M({id:'@id'}))         console.log(M({increment:'@increment'}))


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM