Mock Server

The previous development project is to cut the map and wait for the background to give us the interface, in the data interaction, business logic. If you want to write business logic before the interface has no number, you have to write fake data yourself.

Several ways to Mock

Write dead data in the front end

Writing a lot of fake data on your own takes time. You have to delete all the docking ports.

Low reuse rate and high cost

Proxy tool interception

Take advantage of Fiddler and Charles’ ability to intercept web requests, intercept the request, and replace the response data with our Mock data.

Cumbersome configuration, constant reuse, cost is also high reuse rate bottom, high cost

Mock Server

Use Node to create a service to accept Http requests, and use mock. js to generate fake data. Using Webpack’s Webpack-dev-server Proxy Proxy, Proxy the interface to the Mock service that is being unleashed.

Express to build services, simple and convenient, high reuse rate, low cost

Set up the project

Create a new Mock folder in the project root directory because you need Node dependencies, or a separate Mock project. I’ll put it in the project root.

Mock/data/getUserInfo.js

Put the interface request configuration under data to store the data returned by the interface

module.exports = {
  code: 0,
  message: "success",
  data: {
    name: "Alice",
    mobile: "182xxxx9999",
    age: 30
  }
};
Copy the code

Mock/api.js stores interface API addresses

let api = {
    getUserInfo: "/api/getUserInfo"
};
module.exports = api;
Copy the code

Mock/config.js integrates API addresses with returned data

const api = {
  getUserInfo: "/api/getUserInfo"
};
const getUserInfo = require("./data/getUserInfo.js");

const config = [
  {
    method: "get",
    url: api.getUserInfo,
    data: getUserInfo
  }
];
module.exports = config;
Copy the code

Mock/server.js Mock/server.js creates a server.js

const express = require("express");

const bodyParser = require("body-parser");
const multipart = require("connect-multiparty");

const config = require("./config");
const app = express();
const multipartMiddleware = multipart();

const Mock = require("mockjs");
const mock = (data, params) = > {
  if (Object.prototype.toString.call(data) === "[object Object]") {
    return Mock.mock(data);
  } else if (typeof data === "function") {
    return Mock.mock(data(params));
  } else {
    return "error: data shold be an object or a function."; }}; app.use(bodyParser.urlencoded({extended: false }));
app.use(bodyParser.json());

config.forEach(({ method, url, data }) = > {
  if (method === "get") {
    app.get(url, (req, res) => {
      res.json(mock(data, req.query));
    });
  } else if (method === "post") {
    app.post(url, multipartMiddleware, (req, res) => {
      res.json(mock(data, req.body));
    });
  } else if (method === "jsonp") {
    app.get(url, (req, res) => {
      const query = req.query;

      const mockData = JSON.stringify(mock(data, req.query));

      const callback =
        "typeof " +
        query.callback +
        ' === "function" && ' +
        query.callback +
        "(" +
        mockData +
        ")"; res.send(callback); }); }});let port = 8081;
process.argv.forEach((arg, index, arr) = > {
  if (arg === "--port") {
    port = arr[index + 1] | |8081;
    return false; }});module.exports = app.listen(port, () => {
  console.log("Mock Server listening on http://localhost:" + port);
});
Copy the code

Mock.js

JS to generate fake data so you don’t have to manually add that data

npm install -save-dev mockjs

The official documentation for the rules can be seen in the documentation. We just need to use the function of generating fake data and let Node intercept Ajax requests

Mock/data/getUserInfo.js

module.exports = {
  code: 0,
  message: "success",
  data: {
    name: "@cname",
    mobile: /^1[385]\d{9}$/,
    "age|18-50": 1,
    "orders|5-10": [
      {
        id: "@id",
        from: "@county(true)",
        to: "@county(true)"}}};Copy the code

You can also use it directly in your project

    const Mock = require("mockjs");
    let data = Mock.mock({
      code: 0,
      message: "success",
      data: {
        name: "@cname",
        mobile: /^1[385]\d{9}$/,
        "age|18-50": 1,
        "orders|5-10": [
          {
            id: "@id",
            from: "@county(true)",
            to: "@county(true)"}}}]); console.log(data)Copy the code

The specific configuration can be viewed on the official website, or quite simple

bodyParser

Node’s middleware, used to parse the request body

npm install –save-dev bodyParser

The format of the request is determined by the header context-type

Application/json json format

Application/OCTEt-stream Raw format (binary)

Text /plain Text format

Application/X-www-form-urlencoded Urlencoded (URL coded)

attribute Default Value Default value role JSON Raw (binary) The text (text) Urlencoded (URL encoding)
inflate true The compression Body Square root Square root Square root Square root
limit 100kb Controls the request body size Square root Square root Square root Square root
revier The second argument to json.parse Square root
strict true True accepts only arrays or objects, false accepts json.parse converted values Square root
type application/octet-stream Determine the type of media to parse Square root Square root Square root Square root
verify Get parsing error messages Square root Square root Square root
defaultCharset utf-8 Coding format Square root
extended 100 False Use QuestString to parse the URL, true use QS to parse the URL Square root
parometerlimit 100 The maximum number of bytes allowed for parameters in the URL Square root
const express = require("express");

const bodyParser = require("body-parser");
const multipart = require("connect-multiparty");

const app = express();
Copy the code

Configuration Mode 1

app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
Copy the code

Configuration Mode 2

let urlencodedParser = bodyParser.urlencoded({ extended: false })

app.post('/api',urlencodedParser,function(req,res){... })Copy the code

Configuration Mode 3

app.use(bodyParser.json({ type:'text/plain' }));
app.use(bodyParser.raw({ type:'application/vn.custom-type' }));
app.use(bodyParser.text({ type:'text/html' }));
Copy the code

You can also replace bodyParser with NPM for body or co-body

connect-multiparty

Node middleware, used to save uploaded files

npm install –save-dev connect-multiparty

This one is a little easier. It’s used to save uploaded files.

But it creates a temporary file on the server and does not delete it. You can use multiparty instead.

However, the connect-Multiparty configuration is simple and enabling Mock is sufficient.

Ok, you can start the mock service and implement the local mock service by using webpack-dev-server Proxy to the port

"node ./mock/server.js"
Copy the code

Finally, the plug-in Concurrently is recommended

CMD CMD CMD CMD CMD CMD CMD CMD CMD CMD CMD CMD We use Concurrently to open two processes

npm install -D concurrently

  "scripts": {
    "start": "webpack-dev-server"."mock": "node ./mock/server.js"."dev": "concurrently \"npm run start\" \"npm run mock\""} note""The escape ofCopy the code

Refer to geek time “perspective front-end engineering”, 8 wrong Webpack teaching, suitable for building from scratch.

Recently, we are iterating on the company’s projects, and now everyone should be modularized in their development. Otherwise, it’s really hard to take over old code. I spent two hours just looking at his business logic.