mock配置

1、目录结构

 

2、配置

(1)vue.config.js


const bodyParser = require('body-parser')
const mockServer = require('./src/utils/mock/server');
const { NODE_ENV, VUE_APP_PORT, VUE_APP_MOCK } = process.env;

devServer: {
        port: VUE_APP_PORT || 8000,
        proxy: {...},
        before: function(app, server) {
            if(NODE_ENV === 'development' && VUE_APP_MOCK === 'true') {
                app.use(bodyParser.json());
                app.use(bodyParser.urlencoded({ extended: false}));
                mockServer(app);
            }
        }
    },

(2)\utils\mock\require-context.js

/**
 * 自定义 require.context
 */
module.exports = function(directory, recursive, regExp) {
    const dir = require('node-dir')
    const path = require('path')
  
    // Assume absolute path by default
    let basepath = directory
  
    if (directory[0] === '.') {
      // Relative path
      basepath = path.join(__dirname, directory)
    } else if (!path.isAbsolute(directory)) {
      // Module path
      basepath = require.resolve(directory)
    }
  
    const keys = dir
      .files(basepath, {
        sync: true,
        recursive: recursive || false
      })
      .filter(function(file) {
        return file.match(regExp || /\.(json|js)$/)
      })
      .map(function(file) {
        return path.join('.', file.slice(basepath.length + 1))
      })
  
    var context = function(key) {
      return require(context.resolve(key))
    }
  
    context.resolve = function(key) {
      return path.join(directory, key)
    }
  
    context.keys = function() {
      return keys
    }
  
    return context
  }

(3)\utils\mock\server.js

/**
 * Mock Server
 */
const requireContext = require('./require-context');
const chokidar = require('chokidar');
const path = require('path');

// 注册 mock 路由
function registerMockRoutes(mockDir, app) {
    let mockLastIndex = 0;
    let mockRoutesLength = 0;
    try {        
        // 导入 /mock 下文件 
        const context = requireContext(mockDir, false, /\.js$/);    
        context.keys().forEach(fileName => {
            // 获取内容
            const mocks = context(fileName);
            for (const key in mocks) {
                const keys = key.replace(/(^\s*)|(\s*$)/g, '').split(' ');
                let ajaxType = 'get';
                let ajaxUrl = '';
                if(keys.length<2) {
                    ajaxUrl = keys[0];
                } else {
                    ajaxType = keys[0].toLowerCase();
                    ajaxUrl = keys[1];
                    if(!['get','post','put','patch','delete','head','options'].includes(ajaxType)) {
                        ajaxType = 'get';
                    }
                }
                if(typeof mocks[key] === 'function') {
                    app[ajaxType](ajaxUrl, mocks[key]);
                    mockLastIndex = app._router.stack.length;
                    mockRoutesLength  = mockRoutesLength + 1;
                    // console.log(app._router.stack.length);
                }
            }
        });
    } catch (error) {
      console.log(error);
    }

    return {
        mockRoutesLength: mockRoutesLength,
        mockStartIndex: mockLastIndex - mockRoutesLength
    }
}

// 删除 mock 路由
function unRegisterMockRoutes(mockDir) {
    Object.keys(require.cache).forEach(i => {
      if (i.includes(mockDir)) {
        delete require.cache[require.resolve(i)]
      }
    })
}

module.exports = app => {
    const mockDir = path.resolve('./mock');
    
    const mockRoutes = registerMockRoutes(mockDir,app);
    let mockRoutesLength = mockRoutes.mockRoutesLength;
    let mockStartIndex = mockRoutes.mockStartIndex;

    // watch files, hot reload mock server
    chokidar.watch(mockDir, {
        ignoreInitial: true
    }).on('all', (event, path) => {
        if (event === 'change' || event === 'add' || event === 'unlink') {
            try {
                // remove mock routes stack
                app._router.stack.splice(mockStartIndex, mockRoutesLength);

                // clear routes cache
                unRegisterMockRoutes(mockDir);

                // rest routes
                const mockRoutes = registerMockRoutes(mockDir,app);
                mockRoutesLength = mockRoutes.mockRoutesLength;
                mockStartIndex = mockRoutes.mockStartIndex;

                console.log(`\n > Mock Server hot reload success! changed  ${path}`)
            } catch (error) {
                console.log(error);
            }

        }
    })
}

(4)\mock\user.js

const mockjs= require('mockjs');
const { VUE_APP_APIHOST } = process.env;
const ajaxHeadersTokenKey = 'x-token';
const mock = {};

mock[`GET ${VUE_APP_APIHOST || ''}/user/info`] = (req, res) => {
    const headers = req.headers;
    if (headers[ajaxHeadersTokenKey] === 'admin') {
        res.send({
          code: 0,
          data: {
            id: 1,
            name: 'Admins',
            avatar: '',
            roles: ['admin'],
          },
        });
    } else {
        res.send({
          code: 10002,
          data: {},
          msg: '未登录',
        });
    }

};

mock[`POST ${VUE_APP_APIHOST || ''}/user/login`] = (req, res) => {
    const { password, username } = req.body;
    const send = { code: 0, data: {}, msg: '' };
    if (username === 'admin' && password === '123456') {
        send['data'] = {
        token: 'admin',
        };
    }else {
        send['code'] = 201;
        send['msg'] = 'Wrong username or password';
    }

    res.send(send);
};

module.exports = {
  ...mock
};

3、使用

import request from '@/utils/request';
export async function accountLogin(params): Promise<any> {
return request({
url: '/user/login',
method: 'POST',
data: params,
});
}
 
request.js 的详细配置:查看 https://www.cnblogs.com/LunuZ/p/15581354.html
posted @ 2021-11-20 15:01  卷叶小树  阅读(369)  评论(0编辑  收藏  举报