当前位置: 首页 > 工具软件 > mock-fs > 使用案例 >

搭建mock-server

翁鸿远
2023-12-01

安装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();
});

项目地址:https://github.com/rainbowChenhong/mock-server.git

转载于:https://www.cnblogs.com/heihei-haha/p/9952531.html

 类似资料: