1. 程式人生 > >搭建mock-server

搭建mock-server

安裝mockjs和express

npm install  mockjs express --save

新建api.json

api.josn主要是放請求的json資料,有新增的請求,只需要在api.json新增即可。

{
  "login": [{
    "url": "/login",
    "desc": "介面描述",
    "res": {
      "message": "成功",
      "code": 1,
      "data": {
        "loginName": "@cword(4,10)"
      }
    }
  }],
  "loginTest": [{
    "url": "/loginTest",
    "desc": "介面描述",
    "res": {
      "message": "成功",
      "code": 1,
      "data": {
        "loginName": "@cword(4,10)"
      }
    }
  }]
}

新建server.js

server.js主要是做mock的伺服器。
1.建立一個服務。
2.讀取api.json檔案內容
3.攔截請求,返回匹配的資料

const express = require('express');
const path = require('path');
const fs = require('fs');
const Mock = require('mockjs');

const app = express();
const port = 5050;
const apiPath = path.join(__dirname, './api.json');
let apiData = {};

app.listen(port, function () {
  console.info('mock server is  listening at ' + port)
});

//讀取檔案
let getApi = () => {
  let readStream = fs.createReadStream(apiPath, {
    encoding: 'utf8'
  });

  readStream.on('data', (chunk) => {
    apiData = JSON.parse(chunk)
  });
  readStream.on('end', () => {
    console.info('讀取已完成..');
  });
}

fs.watchFile(apiPath, () => {
  getApi();
  console.info('mock server update');
});

getApi();

app.use((req, res, next) => {
  const originalUrl = req.originalUrl;
  let data = undefined;
  //匹配路徑
  for (let url in apiData) {
    let findItem = apiData[url].find((result) => {
      if (result.url === originalUrl) {
        return result
      }
    });
    if (findItem !== undefined) {
      data = Mock.mock(findItem.res);
      break;
    }
  }
  res.set('Access-Control-Allow-Origin', '*');
  res.set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
  res.set('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization');
  //返回資料
  data !== undefined ? res.send(data) : res.sendStatus(404);
  next();
});