Menu
快讀
  • 旅遊
  • 生活
    • 美食
    • 寵物
    • 養生
    • 親子
  • 娛樂
    • 動漫
  • 時尚
  • 社會
  • 探索
  • 故事
  • 科技
  • 軍事
  • 国际
快讀

Mock.js入門

2021 年 3 月 11 日 白菜小娱乐家

一、Express入門

1、安裝

新建一個目錄,切換到當前目錄下,npm init 初始化package.json

liujiangdeMacBook-Air:Mockjs liujiang$ npm init This utility will walk you through creating a package.json file. It only covers the most common items, and tries to guess sensible defaults. ​ See `npm help json` for definitive documentation on these fields and exactly what they do. ​ Use `npm install <pkg>` afterwards to install a package and save it as a dependency in the package.json file. ​ Press ^C at any time to quit. package name: (mockjs)

輸入項目名:例如expressdemo(注意單詞不能有大寫字母)

輸入版本:1.0.0

項目描述description:excpressDemo

入口(默認是index.js):可以改成app.js

test command:跳過

git repository:跳過

keywords:excrepss

作者:

license:跳過

About to write to /Users/liujiang/Documents/HBuilderProjects/Mockjs/package.json: ​ { “name”: “express”, “version”: “1.0.0”, “description”: “excpressDemo”, “main”: “app.js”, “scripts”: {   “test”: “echo \”Error: no test specified\” && exit 1″ }, “keywords”: [   “express” ], “author”: “liujiang”, “license”: “ISC” } ​ ​ Is this OK? (yes) yes ​ ​   ╭───────────────────────────────────────────────────────────────╮   │                                                               │   │       New minor version of npm available! 6.4.1 → 6.6.0       │   │   Changelog: https://github.com/npm/cli/releases/tag/v6.6.0   │   │               Run npm install -g npm to update!               │   │                                                               │   ╰───────────────────────────────────────────────────────────────╯ ​ liujiangdeMacBook-Air:Mockjs liujiang$

成功!

2、HelloExpress

const express = require(‘express’) const app = express() ​ app.get(‘/’, (req, res) => res.send(‘Hello World!’)) ​ app.listen(3000, () => console.log(‘Example app listening on port 3000!’))

  • 先創建app.js
  • 把代碼粘貼過去
  • 運行 node app.js
  • 報錯Error: Cannot find module ‘express’,因爲沒有依賴
  • 安裝依賴,npm install express –save,—save安裝到package.json{
    “name”: “expressdemo”,
    “version”: “1.0.0”,
    “description”: “excpressDemo”,
    “main”: “app.js”,
    “scripts”: {
    “test”: “echo \”Error: no test specified\” && exit 1″
    },
    “keywords”: [
    “express”
    ],
    “author”: “liujiang”,
    “license”: “ISC”,
    “dependencies”: {
    “express”: “^4.16.4″//添加了依賴
    }
    }
  • 運行 node app.js 訪問http://localhost:3000/,成功!control+c停止

二、使用生成器快速構建

通過應用生成器工具 express-generator 可以快速創建一個應用的骨架。

express-generator 包含了 express 命令行工具。通過如下命令即可安裝:

$ npm install express-generator -g

-h 參數可以列出所有可用的命令行參數:

$ express -h ​ Usage: express [options] [dir] ​ Options: ​    -h, –help         輸出使用方法        –version       輸出版本號    -e, –ejs           添加對 ejs 模板引擎的支持        –hbs           添加對 handlebars 模板引擎的支持        –pug           添加對 pug 模板引擎的支持    -H, –hogan         添加對 hogan.js 模板引擎的支持        –no-view       創建不帶視圖引擎的項目    -v, –view <engine> 添加對視圖引擎(view) <engine> 的支持 (ejs|hbs|hjs|jade|pug|twig|vash) (默認是 jade 模板引擎)    -c, –css <engine> 添加樣式表引擎 <engine> 的支持 (less|stylus|compass|sass) (默認是普通的 css 文件)        –git           添加 .gitignore    -f, –force         強制在非空目錄下創建

例如,如下命令創建了一個名稱爲 demo 的 Express 應用。此應用將在當前目錄下的 Mockjs 目錄中創建:

liujiangdeMacBook-Air:Mockjs liujiang$ mkdir demo liujiangdeMacBook-Air:Mockjs liujiang$ cd demo liujiangdeMacBook-Air:Mockjs liujiang$ express demo liujiangdeMacBook-Air:demo liujiang$ npm install

在 MacOS 或 Linux 中,通過如下命令啓動此應用:

$ npm start//這裏需進入第二個demo的路徑,下次可以不這麽創建項目,直接新建一個項目,按照官網進行

然後在浏覽器中打開 http://localhost:3000/ 網址就可以看到這個應用了。

通過生成器創建的應用一般都有如下目錄結構:

. ├── app.js ├── bin │   └── www ├── package.json ├── public │   ├── images │   ├── javascripts │   └── stylesheets │       └── style.css ├── routes │   ├── index.js │   └── users.js └── views   ├── error.pug   ├── index.pug   └── layout.pug ​ 7 directories, 9 files

三、supervisor

1、修改內容

在routers下的index.js

var express = require(‘express’); var router = express.Router(); ​ /* GET home page. */ router.get(‘/’, function(req, res, next) {  res.render(‘index’, { title: ‘Express–test’ });//修改 }); ​ module.exports = router; ​

需要重啓,npm start,很麻煩

2、安裝

npm install -g supervisor

3、啓動

supervisor ./bin/www

在更改內容後就不要再啓動了,直接刷新就好了

四、初始Mock.js

1、什麽是Mock.js

是一款模擬數據的生成器,讓前端工程師獨立開發,不依賴後端

2、Mock.js能做什麽

  • 根據數據模板生成模擬數據
  • 模擬ajax請求,生成並返回數據
  • 基于html模板生成模擬數據

3、爲什麽用Mockjs

  • 開發時,後端還沒完成數據輸出,前端只能寫好靜態模擬數據,數據太長了,將數據寫在js文件裏,完成後挨個改url。
  • 某些邏輯複雜的代碼,加入或去除模擬數據時容易出錯
  • 想要盡可能還原真實的數據,要麽編寫更多的代碼,要麽手動修改模擬數據
  • 特殊的格式,例如ip,隨機數,圖片,地址,需要去收集,分頁顯示

4、如何正確使用Mockjs

  • 安裝 npm install mockjs
  • 使用

var Mock = require(‘mockjs’); var data = Mock.mock({   ‘list|1-10’:[{       ‘id|+1’:1   }] }); console.log(JSON.stringify(data,null,4))

  • 加載Mock

<script src = “http://mockjs.com/dist/mock.js”></script>

五、Node中集成Mock

1、安裝

  • 新建項目文件夾 node_mock
  • npm install mockjs
  • 新建demo.js
  • copy上面的使用代碼
  • 運行 node demo.js{
    “list”: [
    {
    “id”: 1
    },
    {
    “id”: 2
    },
    {
    “id”: 3
    },
    {
    “id”: 4
    },
    {
    “id”: 5
    },
    {
    “id”: 6
    },
    {
    “id”: 7
    }

2、融合Express

  • 使用之前的express項目(切換到項目目錄),將mockjs打包到express
  • npm install mockjs –save

{  “name”: “demo”,  “version”: “0.0.0”,  “private”: true,  “scripts”: {    “start”: “node ./bin/www” },  “dependencies”: {    “cookie-parser”: “~1.4.3”,    “debug”: “~2.6.9”,    “express”: “~4.16.0”,    “http-errors”: “~1.6.2”,    “jade”: “~1.11.0”,    “mockjs”: “^1.0.1-beta3”,    “morgan”: “~1.9.0” } }

  • 使用supervisor啓動 supervisor ./bin/www
  • 切換到路由 routes/index.js
  • 修改var express = require(‘express’);
    var router = express.Router();
    ​
    /* GET home page. */
    router.get(‘/’, function (req, res, next) {
    res.render(‘index’, { title: ‘Express–supervisor’ });
    });
    // mock
    router.get(‘/mock’, function (req, res, next) {
    var Mock = require(‘mockjs’);
    var data = Mock.mock({
    ‘list|1-10’: [{
    ‘id|+1’: 1
    }]
    });
    var result = JSON.stringify(data, null, 4);
    res.render(‘index’, { title: result });
    });
    //有html的
    //使用send方法,注意兩者的區別
    router.get(‘/mock’, function (req, res, next) {
    var Mock = require(‘mockjs’);
    var data = Mock.mock({
    ‘list|1-10’: [{
    ‘id|+1’: 1
    }]
    });
    var result = JSON.stringify(data, null, 4);
    res.send(result);
    });
    module.exports = router;
    ​

六、mockjs語法規範

1、數據模板的定義DTD

  • String
  • Number
  • Boolean
  • Object
  • Array
  • function

數據模板中的每個屬性由 3 部分構成:屬性名、生成規則、屬性值:

// 屬性名   name // 生成規則 rule // 屬性值   value ‘name|rule’: value

注意:

  • 屬性名 和 生成規則 之間用豎線 | 分隔。
  • 生成規則 是可選的。
  • 生成規則 有 7 種格式:’name|min-max’: value’name|count’: value’name|min-max.dmin-dmax’: value’name|min-max.dcount’: value’name|count.dmin-dmax’: value’name|count.dcount’: value’name|+step’: value
  • 生成規則 的 含義 需要依賴 屬性值的類型 才能確定。
  • 屬性值 中可以含有 @占位符。
  • 屬性值 還指定了最終值的初始值和類型。

生成規則和示例:

1.1. 屬性值是字符串 String

  1. ‘name|min-max’: string通過重複 string 生成一個字符串,重複次數大于等于 min,小于等于 max。
  2. ‘name|count’: string通過重複 string 生成一個字符串,重複次數等于 count。

1.2. 屬性值是數字 Number

  1. ‘name|+1’: number屬性值自動加 1,初始值爲 number。
  2. ‘name|min-max’: number生成一個大于等于 min、小于等于 max 的整數,屬性值 number 只是用來確定類型。
  3. ‘name|min-max.dmin-dmax’: number生成一個浮點數,整數部分大于等于 min、小于等于 max,小數部分保留 dmin 到 dmax 位。

Mock.mock({   ‘number1|1-100.1-10’: 1,   ‘number2|123.1-10’: 1,   ‘number3|123.3’: 1,   ‘number4|123.10’: 1.123 }) // => {   “number1”: 12.92,   “number2”: 123.51,   “number3”: 123.777,   “number4”: 123.1231091814 }

1.3. 屬性值是布爾型 Boolean

  1. ‘name|1’: boolean隨機生成一個布爾值,值爲 true 的概率是 1/2,值爲 false 的概率同樣是 1/2。
  2. ‘name|min-max’: value隨機生成一個布爾值,值爲 value 的概率是 min / (min + max),值爲 !value 的概率是 max / (min + max)。

1.4. 屬性值是對象 Object

  1. ‘name|count’: object從屬性值 object 中隨機選取 count 個屬性。
  2. ‘name|min-max’: object從屬性值 object 中隨機選取 min 到 max 個屬性。

1.5. 屬性值是數組 Array

  1. ‘name|1’: array從屬性值 array 中隨機選取 1 個元素,作爲最終值。
  2. ‘name|+1’: array從屬性值 array 中順序選取 1 個元素,作爲最終值。
  3. ‘name|min-max’: array通過重複屬性值 array 生成一個新數組,重複次數大于等于 min,小于等于 max。
  4. ‘name|count’: array通過重複屬性值 array 生成一個新數組,重複次數爲 count。

1.6. 屬性值是函數 Function

  1. ‘name’: function執行函數 function,取其返回值作爲最終的屬性值,函數的上下文爲屬性 ‘name’ 所在的對象。{
    ‘title’:’hello mockjs’,
    ‘function’:function(){
    return this,title
    }
    }
    ->
    {
    “title”:”hello mockjs”,
    “function”:”hello mockjs”
    }

1.7. 屬性值是正則表達式 RegExp

  1. ‘name’: regexp根據正則表達式 regexp 反向生成可以匹配它的字符串。用于生成自定義格式的字符串。Mock.mock({
    ‘regexp1’: /[a-z][A-Z][0-9]/,
    ‘regexp2’: /\w\W\s\S\d\D/,
    ‘regexp3’: /\d{5,10}/
    })
    // =>
    {
    “regexp1”: “pJ7”,
    “regexp2”: “F)\fp1G”,
    “regexp3”: “561659409”
    }

2、數據占位符的定義DPD

占位符 只是在屬性值字符串中占個位置,並不出現在最終的屬性值中。

占位符 的格式爲:

@占位符 @占位符(參數 [, 參數])

注意:

  1. 用 @ 來標識其後的字符串是 占位符。
  2. 占位符 引用的是 Mock.Random 中的方法。
  3. 通過 Mock.Random.extend() 來擴展自定義占位符。
  4. 占位符 也可以引用 數據模板 中的屬性。
  5. 占位符 會優先引用 數據模板 中的屬性。
  6. 占位符 支持 相對路徑 和 絕對路徑。

Mock.mock({    name: {        first: ‘@FIRST’,        middle: ‘@FIRST’,        last: ‘@LAST’,        full: ‘@first @middle @last’   } }) // => {    “name”: {        “first”: “Charles”,        “middle”: “Brenda”,        “last”: “Lopez”,        “full”: “Charles Brenda Lopez”   } }

七、訪問

//用send方法 router.get(‘/mock1’, function (req, res, next) {  var Mock = require(‘mockjs’);  var data = Mock.mock({    “array|1-10”: [     {        “name|+1”: [          “Hello”,          “Mock.js”,          “!”       ]     }   ] });  var result = JSON.stringify(data, null, 4);  res.send(result); });

八、ajax的跨域實現

var express = require(‘express’); var router = express.Router(); ​ /* GET home page. */ router.get(‘/’, function (req, res, next) {  res.render(‘index’, { title: ‘Express–supervisor’ }); }); // mock router.get(‘/mock’, function (req, res, next) {  var Mock = require(‘mockjs’);  var data = Mock.mock({    ‘list|1-10’: [{      ‘id|+1’: 1   }] });  var result = JSON.stringify(data, null, 4);  res.render(‘index’, { title: result }); }); //用send方法 router.get(‘/mock1’, function (req, res, next) {  var Mock = require(‘mockjs’);  var data = Mock.mock({    ‘categorys|3-5′:[{      categoryName:’@cname’,      ‘categoryID|+1′:10, ​      logo:’@image(64×64,#eee,Logo)’,      ‘categoryItems|1-4′:[{ ​        cname:’@cname’,        ‘cid|+1’:100,        ‘item|3-7′:[{ ​          name:’@cname’,          ‘id|+1′:1000,          link:’@url’       }]     }],      ‘seller|8-15′:[{        name:’@cname@cname’,        url:’@url’     }]   }] });  var result = JSON.stringify(data, null, 4);  // 以ajax跨域 jsonp請求  var callback = req.query.callback;  result = callback+”(“+result+”)”;  res.send(result); }); module.exports = router; ​<!DOCTYPE html> <html> <head>    <meta charset=”utf-8″ />    <meta http-equiv=”X-UA-Compatible” content=”IE=edge”>    <title>Page Title</title>    <meta name=”viewport” content=”width=device-width, initial-scale=1″>    <script src=”http://code.jquery.com/jquery-latest.js”></script>    <script>        console.log(‘aaa’)        var urlstr = ‘http://localhost:3000/mock1′;        $.ajax({            type:’get’,            async:false,            url:urlstr,            cache:false,            dataType:’jsonp’,            success : function(json){                console.log(json);           },            error:function(e){                console.log(e);           } ​       })    </script> </head> <body>     </body> </html>

九、前端數據綁定

<script>    var urlstr = ‘http://localhost:3000/mock1′;    $.ajax({        type:’get’,        async:false,        url:urlstr,        cache:false,        dataType:’jsonp’,        success : function(json){            // console.log(json);            $(‘.right li’).html(”);            $(json.categorys).each(function(i,categorys){                // console.log(i+categorys)                $(categorys.categoryItems).each(function(i,categoryItems){                    console.log(i+categoryItems.cname)                    $(‘.right li’).html(categoryItems.cname);               })           }) ​       },        error:function(e){            console.log(e);       } ​   }) </script>

十、項目發布

  • 使用全局組件的盡量放到package.json
  • 不放入packagejson時,需要在發布的及其上安裝全劇組件
  • 不清楚使用哪些全局組件,在目標機器上部署後,根據報錯信息添加npm install mockjs –save //–node modules(本地)

1、整體發布

  • 所有都會發布
  • 本地不會丟失
  • 組件包發布後會非常大,打包也會變慢

2、源代碼發布

  • 體積比較小
  • 發布本地包,全局在分別處理

3、壓縮包

通過壓縮包形式打包,不要node_modules文件夾,會根據package.json npm install初始化

var Mock = require(‘mockjs’); var data = Mock.mock({    ‘news|5-10’:[{        ‘id|+1′:1,        title:’@title’,        text:’@cparagraph’,        time:’@date’,        number:’@integer(1, 1000)’,        image:’@image(42×42,#eee,Logo)’   }] }); console.log(JSON.stringify(data,null,4))

相關文章:

  • 6月份開放申請的一馬房屋計劃(PR1MA)
  • 2020年全球130個航展速覽,珠海航展將在11月10日舉辦
  • Spring 源碼學習(十) Spring mvc
  • 2 月球鞋發售清單:重磅狠貨太多!侃爺 7 雙新鞋死磕 12 雙 AJ
  • 全球空中力量排行榜TOP96,中國有3支部隊上榜
  • 函數式編程:Ramda 函數庫參考教程
旅遊

發佈留言 取消回覆

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

©2025 快讀 | 服務協議 | DMCA | 聯繫我們