Mock-server is a scripting tool for quickly setting up a data server for your development environment. All you need to start the server is a mockJS template file.

The script will start the local server and then match the URL within the mock template to return the corresponding data

use

# global install
npm i @shymean/mock-server -g
# Quick start mock server
mock -p 9999 -f ./_mock.js
Copy the code

Parameters that

  • Port: indicates the server port number. The default value is 7654. -p for short
  • File, mock template file path, default./_mock.js, short – f

Mockjs template syntax

To use the tool, you only need to prepare a mock template file with a syntax reference

  • Internally, @shymean/koa-mock is used, which is a middleware for quickly building koA’s mock server
  • Mock templates use the MockJS syntax and extend related functionality
// _mock.js
// The corresponding RURL is intercepted by the middleware and the mock data is returned
// ANY localhost:9999/
Mock.mock('/', {
    data: [].msg: "hello mock"."code|1-4": 1,})// Request methods that can be mock
// POST localhost:9999/test
Mock.mock('/test'.'POST', {
    data: [].msg: "hello mock"."code|1-4": 1,})// Extend rtype to support the jSONp form, using param to pass in the corresponding callback name
// GET JSONP localhost:9999/test
Mock.mock('/test', {
    type: 'jsonp'.param: 'callbackName'}, {code: 0.msg: 'hello from mock jsonp'.data: {
        "id|1000-9999": 1,}})// The default callback name is callback
Mock.mock("/test2"."jsonp", {
    code: 0.msg: "hello from mock jsonp2".data: {
        "id|1000-9999": 1,}});Copy the code

Custom request header matching

The Mock. ParseUrl method is implemented in the template file. This method returns an RURL for matching

Mock.parseUrl = function(ctx){
    // CTX is koA context object
    return 'someUrl'
}

Mock.mock('someUrl', {code: 0})
Copy the code

Nginx configuration

To avoid using the localhost domain name in business code, it is a best practice to point the business domain name (e.g. Xxx.test.com) locally at development time

127.0.0.1 xxx.test.com
Copy the code

Then configure the reverse proxy to the mock server via Nginx

server {
    listen 80;
    server_name xxx.test.com;

    Determine which interface needs to use mock data based on location
    location /j/cn/control/api {
        proxy_set_header X-Real-IP $remote_addr;
        proxy_set_header X-Forward-For $proxy_add_x_forwarded_for;
        proxy_set_header Host $http_host;
        proxy_pass http://127.0.0.1:9999; The port number of the server started by the # mock -p 9999 directive}}Copy the code

Feature

  • Share the same set of mock templates with the MockJS browser side for easy migration and code maintenance
  • Support for JSONP requests
  • Data template hot update. After the template file is modified, the server automatically restarts

Todo

  • Support for mapping local files, such as style sheets, images, etc