mock.js-no need to wait for the front end to be developed independently of the backend

Source: Internet
Author: User

Overview
    • First of all, I do not know the author of Mock.js, with the need to find mock.js I feel very amazing.
    • Compared to the implementation of other similar frameworks, mock.js exceeded my expectations.
      • Generate simulation data based on a data template.
      • Generate simulation data based on HTML templates.
      • Intercepts and simulates Ajax requests.
    • Yes, mock.js only do a few of the above, but do it well enough.
The problem solved

Development, the backend has not finished the data output, the front end had to write static simulation data.

    • The data is too long, write the data in the JS file, and then change the URL.
    • Some logically complex code that is cautious when adding or removing analog data.
    • To try to restore real data as much as possible, either write more code or manually modify the simulation data.
    • Special formats, such as IP, random numbers, pictures, addresses, need to be collected.
    • Super Rotten Speed ...
    • ...
Problems encountered during use and corresponding solutions

1. The project is based on SEAJS, so the data template cannot be loaded dynamically based on whether the URL contains a parameter mock.

    • code example:
      ~location.search.indexof (' mock ') && require (' Mock/index ');
    • Background: In order to control whether analog data is enabled we will add a mock parameter to the URL, the mock will load the data template, no load, but the above code does not achieve this purpose, regardless of the URL has no mock parameters, will load the data template
    • Reason: Because SEAJS internal pre-loading mechanism, as long as the code in the Require a file, it will parse the file dependencies, thereby downloading these files;
    • Workaround:
      var module = [' Page/index/index ']; if (~location.search.indexof (' mock '))    Module.push (' mock/index '); Seajs.use (function (Router) {    router.ready (  Params, index) {        index.init (params);    }, module);});

      Here, we solve this problem by dynamically selecting the module that needs to be loaded asynchronously, depending on whether the URL contains a mock, in the HTML page Entry section.

2. The project uses Net.js to encapsulate AJAX requests in a layer that cannot intercept AJAX requests.

  • code example:
    Mock.mock (' A.json ', {result:0, ErrMsg:' OK ', data: {' List|0-10 ': [{                ' Icon ': ' @image ',                ' Nick ': ' @name ',                ' Invitetime ': ' @date '            }],            ' Hasmore|0-1 ': 1,            ' Invitepeoplenum|1-50 ': 20,            ' getawardnum|10-600 ': 12,            ' Hasaward|0-1 ': 1        }    }); Net.ajax ({URL:' A.json ', Data: {module:"Invite_chest_box", Method:"Getinvitelist", param: {"tt": "2",                "AppId": "1000001034",                "PageNo": 0,                "PageCount": 10}}, Cache:false, DataType:' JSON ', Success:function(JSON) {//Callback after successConsole.log (JSON)}});
  • Background: Mock.js Because of the default built-in jquery, Zepto, Kissy blocking AJAX requests, Ajax requests cannot be intercepted because our project specifically encapsulates the AJAX request.
  • Solution:
    var net = require (' util/net '); Mock.mockjax (net);

    Call the Mackjax method to inject the interception operation into the Net.ajax to intercept Ajax before it takes effect.

3. A project CGI name and module name are the same, different interfaces using method to differentiate, through method can not distinguish between different interfaces and block Ajax requests.

  • code example:
    Mock.mock (/getinvitelist/, {result:0, ErrMsg:' OK ', data: {' List|0-10 ': [{                ' Icon ': ' @image ',                ' Nick ': ' @name ',                ' Invitetime ': ' @date '            }],            ' Hasmore|0-1 ': 1,            ' Invitepeoplenum|1-50 ': 20,            ' getawardnum|10-600 ': 12,            ' Hasaward|0-1 ': 1        }    }); $.ajax ({URL:' http://gift.gamecenter.qq.com/cgi-bin/gc_invite_chest_box_fcgi ', Data: {module:"Invite_chest_box", Method:"Getinvitelist", param: {"tt": "2",                "AppId": "1000001034",                "PageNo": 0,                "PageCount": 10}}, Cache:false, DataType:' JSON ', Success:function(JSON) {//Callback after successConsole.log (JSON)}});

    The first parameter of Mock.mock is a matching rule, either a string or a regular, here we use the CGI method to match the current CGI, but unfortunately there is no match to the

  • Reason:

View source we found that when the matching rule is a string, the matching rule must be exactly the same as the request URL, and when the matching rule is regular, you need to check for a match on the request URL, so whether it's a string match or a regular match, it just looks for a match on the URL. does not match parameters within the data (such as Method:getinvitelist)

    • Solution:

Here the options inside the data objects are also included in the check matching category, are to match the two checks are changed to a regular match, are ignoring the letter case, so that we can be based on any parameters within the data to match different CGI requests, greatly improved the flexibility of matching.

View the results of a response
{    "Result": 0,    "ErrMsg": "OK",    "Data": {        "List": [            {                "Icon": "http://dummyimage.com/120x600",                "Nick": "Charles Hernandez",                "Invitetime": "1988-09-26"            },            {                "Icon": "http://dummyimage.com/120x60",                "Nick": "Linda Garcia",                "Invitetime": "1991-09-14"            }        ],        "Hasmore": 0,        "Invitepeoplenum": 45,        "Getawardnum": 511,        "Hasaward": 0    }}

mock.js-no need to wait for the front end to be developed independently of the backend

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.