モックサーバー構造(マイクロチャネルアプレット)

モックサーバー構造(マイクロチャネルアプレット)

小さなマイクロチャネルプログラムにmock.jsを使用する方法は本当に問題であり、完全なルーティングおよびデータ・アクセスをシミュレートするために、ローカルモックサーバーを構築することを選択する良い選択です。

以下は偽サーバと学生対象例CRUDページングを構築するプロセスを示します。

前提条件

インストールのNode.js

サーバーを作成します。

  1. 私たちは、新しいフォルダを作成mockServer vscodeでフォルダを開き、お使いのコンピュータ上の場所を選択しました
  2. 以下のモジュールをインストールするには、コマンドを使用します
cnpm install express body-parser cors nodemon mockjs --save
  • Node.jsの枠組みを表現
  • URLを解析するためのボディパーサー
  • クロスドメインの問題を解決するために使用CORS
  • nodemon手動でサーバーの問題を再起動するために必要なコードの変更を解決するため、nodemonは、サーバを起動するために、自分でコードの変更を検出し、
  • mockjsモックシミュレーションツール
  1. ファイルやディレクトリの確立

(1)npm init -f生成しpackage.jsonたファイルを

nodemon使用するようにスタートを変更

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

(2)server.jsファイルを作成し、模擬ディレクトリ

mockServerディレクトリ

  1. server.js次のテストのためにコードを書く、入力制御部は、npm startサーバを起動します
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}`);
});

コンソール意志出力服务器启动,运行为http://localhost:8081、我々はブラウザで訪問http://localhost:8081/posts、次はそのサーバーが正常に作成され、表示されます。

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

モックインターフェイスを作成します。

  1. モックフォルダに新しい2つのファイルが1 index.jsルートを宣言するため、student.js学生はオペレーションコードに関連するオブジェクトをシミュレート調製するために使用され、。
  2. 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. ルートを定義します
//  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. server.js導入index.js文書を、ポスト・インターフェースの定義を削除
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}`);
});

テストインタフェース

以下は、テストコードで書かれた小さなプログラムであります

<!--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('访问完成');
      }
    })
  }
})

次のように返された結果は以下のとおりです。

  1. 学生は情報を得ます

学生は情報を得ます

  1. 生徒の情報を削除します

生徒の情報を削除します

3.新しい学生情報

新しい学生情報

  1. 学生情報を更新

学生情報を更新

PS:IDのフロントが削除されているので、ので、この時間は更新が文句を言うでしょう

  1. 個々の学生のIDを照会するためによると

個々の学生のIDを照会するためによると

2019年5月31日午後06時56

おすすめ

転載: www.cnblogs.com/yejingping/p/10956983.html