Mock server structures (micro-channel applet)

Mock server structures (micro-channel applet)

How to use mock.js in small micro-channel program is really a problem, in order to fully simulate the routing and data access, choose to build local mock server is a good choice.

The following illustrates the process of building a mock server and student-object example CRUD paging.

Prerequisites

Node.js installed

Create a server

  1. We chose a location on your computer, create a new folder mockServer, open the folder with vscode
  2. Use the command to install the following modules
cnpm install express body-parser cors nodemon mockjs --save
  • express node.js framework
  • body-parser for parsing url
  • cors used to solve cross-domain problems
  • nodemon solve the code changes required to manually restart the server problem, nodemon detects code changes on their own to start the server
  • mockjs mock simulation tool
  1. The establishment of files and directories

(1) npm init -fgenerate a package.jsonfile

Modify start to use nodemon

"scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "start": "nodemon server.js"
  },

(2) create server.js file, mock directory

mockServer directory

  1. In server.jswriting the code for the following test, the input control section npm startto start the server
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

app.get('/posts', (req, res) => {
  res.send([
    {
      title: 'Hello World!',
      description: 'Hi there! How are you?'
    }
  ]);
});

//  指定端口
const PORT = 8081;

app.listen(PORT, () => {
  console.log(`服务器启动,运行为http://localhost:${PORT}`);
});

The console will output 服务器启动,运行为http://localhost:8081; we visited in the browser http://localhost:8081/posts, the following appears, then that server is created successfully.

[
    {
    "title": "Hello World!",
    "description": "Hi there! How are you?"
    }
]

Create a mock Interface

  1. New in mock folder two files, one index.jsfor declaring route, a student.js, used to prepare students simulate objects related to the operation code.
  2. Preparation of related operation code in student.js
//  student.js
const Mock = require('mockjs');
let list = [];
const count = 100;

for (let i = 0; i < count; i++) {
  list.push(
    Mock.mock({
      id: '@increment',
      stuNo: 20220000 + parseInt(`${i + 1}`),
      stuName: '@cname',
      stuGender: '@integer(0,1)',
      stuPhone: /^1[0-9]{10}$/,
      stuBirthday: '@date("yyyy-MM-dd")',
      classNo: '@integer(201901,201912)'
    })
  );
}

//  增加学生
exports.add = (req, res) => {
  const { classNo, stuBirthday, stuGender, stuName, stuPhone } = req.body;
  list.push({
    id: list[list.length - 1].id + 1,
    stuNo: list[list.length - 1].stuNo + 1,
    classNo: classNo,
    stuBirthday: stuBirthday,
    stuGender: stuGender,
    stuName: stuName,
    stuPhone: stuPhone
  });
  let msg = {
    code: 20000,
    data: {
      listNum: list.length,
      message: '添加成功!'
    }
  };
  res.status(200).json(msg);
};

//  删除学生
exports.delete = (req, res) => {
  const id = req.params.id;

  //  判断id是否存在
  let flag = list.some(item => {
    if (item.id == id) {
      return true;
    }
  });

  if (flag) {
    // id 存在
    list = list.filter(item => item.id !== parseInt(id));
    const msg = {
      code: 20000,
      data: {
        listNum: list.length,
        message: '删除成功!'
      }
    };
    res.status(200).json(msg);
  } else {
    //  id不存在
    const msg = {
      code: 40000,
      data: {
        msg: 'id不存在!'
      }
    };
    res.status(500).json(msg);
  }
};
//  更新学生信息
exports.update = (req, res) => {
  const { id, classNo, stuBirthday, stuGender, stuName, stuPhone } = req.body;

  //  判断id是否存在
  let flag = list.some(item => {
    if (item.id == id) {
      return true;
    }
  });

  if (flag) {
    //  id存在
    list.some(item => {
      if (item.id === id) {
        item.classNo = classNo;
        item.stuBirthday = stuBirthday;
        item.stuGender = stuGender;
        item.stuName = stuName;
        item.stuPhone = stuPhone;
      }
    });
    let msg = {
      code: 20000,
      data: {
        message: '更新成功!'
      }
    };
    res.status(200).json(msg);
  } else {
    //  id不存在
    const msg = {
      code: 40000,
      data: {
        msg: 'id不存在!'
      }
    };
    res.status(500).json(msg);
  }
};
//  查询学生信息
exports.find = (req, res) => {
  let { queryStr, page = 1, limit = 10 } = req.body;
  //  根据学生姓名查询学生或者返回所有学生信息

  const mockList = queryStr && queryStr.length > 0 ? list.filter(item => item.stuName.includes(queryStr)) : list;
  //  数据分页
  const pageList = mockList.filter((item, index) => index < limit * page && index >= limit * (page - 1));
  let msg = {
    code: 20000,
    count: mockList.length,
    data: pageList
  };
  res.status(200).json(msg);
};

//  根据id返回学生信息
exports.findById = (req, res) => {
  const id = req.query.id;
  const pageList = list.filter(item => item.id == id);
  const msg = {
    code: 20000,
    data: pageList
  };
  res.status(200).json(msg);
};
  1. Define the route
//  index.js
module.exports = function(app) {
  const student = require('./student');

  //  新增学生
  app.post('/student/add', student.add);

  //  删除学生
  app.delete('/student/delete/:id', student.delete);

  //  更新学生信息
  app.put('/student/update', student.update);

  //  查询学生信息
  app.post('/student/list', student.find);

  //  查询单个学生接口
  app.get('/student', student.findById);
};
  1. In server.jsintroducing the index.jsdocument, delete the definition of posts interfaces
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');

const app = express();
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
app.use(cors());

//  引入路由文件
require('./mock/index')(app);

//  指定端口
const PORT = 8081;

app.listen(PORT, () => {
  console.log(`服务器启动,运行为http://localhost:${PORT}`);
});

Test Interface

The following is a small program written in the test code

<!--index.wxml-->
<view class="container">
  <button catchtap='getStudent'>获取学生信息</button>
  <button catchtap='deleteStudent'>删除学生信息</button>
  <button catchtap='addStudent'>新增学生信息</button>
  <button catchtap='updateStudent'>更新学生信息</button>
  <button catchtap='findStudent'>查询单个学生</button>
</view>
//index.js
//获取应用实例
const app = getApp()

Page({
  data: {},
  getStudent:function(){
    wx.request({
      url: 'http://localhost:8081/student/list',
      data:{
        queryStr:'',
        page:1,
        limit:10
      },
      method: 'POST',
      success: function (res) {
        console.log('访问成功:', res);
      },
      fail: function (e) {
        console.log('访问失败:', e);
      },
      complete: function () {
        console.log('访问完成');
      }
    })
  },
  deleteStudent:function(){
    wx.request({
      url: 'http://localhost:8081/student/delete/1',
      method: 'DELETE',
      success: function (res) {
        console.log('访问成功:', res);
      },
      fail: function (e) {
        console.log('访问失败:', e);
      },
      complete: function () {
        console.log('访问完成');
      }
    })
  },
  addStudent:function(){
    wx.request({
      url: 'http://localhost:8081/student/add',
      data:{
        classNo:'201901',
        stuBirthday:'2019-05-31',
        stuGender:0,
        stuName:'李小珍',
        stuPhone:'12345678910'
      },
      method: 'POST',
      success: function (res) {
        console.log('访问成功:', res);
      },
      fail: function (e) {
        console.log('访问失败:', e);
      },
      complete: function () {
        console.log('访问完成');
      }
    })
  },
  updateStudent:function(){
    wx.request({
      url: 'http://localhost:8081/student/update',
      data: {
        id:1,
        classNo: '201901',
        stuBirthday: '2019-05-31',
        stuGender: 0,
        stuName: '李小珍',
        stuPhone: '12345678910'
      },
      method: 'PUT',
      success: function (res) {
        console.log('访问成功:', res);
      },
      fail: function (e) {
        console.log('访问失败:', e);
      },
      complete: function () {
        console.log('访问完成');
      }
    })
  },
  findStudent:function(){
    wx.request({
      url: 'http://localhost:8081/student?id=2',
      data: {},
      method: 'GET',
      success: function (res) {
        console.log('访问成功:', res);
      },
      fail: function (e) {
        console.log('访问失败:', e);
      },
      complete: function () {
        console.log('访问完成');
      }
    })
  }
})

Returned results are as follows:

  1. Students get information

Students get information

  1. Delete student information

Delete student information

3. New Student Information

New Student Information

  1. Update student information

Update student information

PS: Because the front of the id is deleted, so this time the update will complain

  1. According to query individual student id

According to query individual student id

2019/05/31 18:56

Guess you like

Origin www.cnblogs.com/yejingping/p/10956983.html