zoukankan      html  css  js  c++  java
  • 搭建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();
    });
    

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

  • 相关阅读:
    ASP.NET MVC 5
    Web Components是不是Web的未来
    如何选择高性价比的控件产品
    ASP.NET MVC 5
    ubuntu系统安装
    Ubuntu linux安装完成后隐藏linux磁盘挂载点
    win10 查看本机的激活秘钥
    windows cmd下列出当前目录下的所有文件
    error LNK2005: “找到一个或多个多重定义的符号” 已经在 xxxx.obj 中定义 的解决方法
    架构设计:负载均衡层设计方案(3)——Nginx进阶
  • 原文地址:https://www.cnblogs.com/heihei-haha/p/9952531.html
Copyright © 2011-2022 走看看