使用Node写一个Mock服务实现思路:读取mock文件夹,遍历.js文件,尝试导入文件内容,将文件内容拼接成对象,以请求类型+空格+请求地址为key,并当在js对象中可以找到接收到的请求时就返回结果,返回404获取文件内容//./src/utils/getMock.jsconstfs=require('fs');constpath=require('路径');constgetMockBundleOfDir=(mockDirPath)=>{//同步读取mock文件夹constfileNameList=fs.readdirSync(mockDirPath);//模拟对象总结letmockBundle={};//遍历文件fileNameList.forEach(fileName=>{constfilePtah=path.resolve(`${mockDirPath}/${fileName}`);//只读取JS文件if(fileName.endsWith('.js')){//容错,文件内容可能有问题){Object.assign(mockBundle,content);}}catch(error){console.log('\033[41;37m',`读取${filePtah}文件时出错`,'\033[0m');}}})返回mockBundle;}module.exports=getMockBundleOfDir;实现解析constKoa=require('koa');constkoaBody=require('koa-body');constloggerAsync=require('./src/middle/log.js');constgetMockBundleOfDir=require('./src/utils/getMock.js');常量toString=对象。原型.toString;constmockDirPath='./src/mock';//模拟目录地址//获取模拟对象集合letmockBundle=getMockBundleOfDir(mockDirPath);constapp=newKoa();app.use(koaBody());//koa插件,用于解析post请求的body//mockrequestapp.use(async(ctx,next)=>{//对应mock请求类型+空格+请求地址的映射constrequest=`${ctx.method}${ctx.path}`;//TODO容错try{constmock=mockBundle[request];constmockType=toString.call(mock);if(mockType==='[objectFunction]'){//模拟数据是函数letquery;if(ctx.m方法==='GET'){query=ctx.query;}elseif(ctx.method==='POST'){query=ctx.request.body;}//返回模拟结果constresponse=mock(query);返回ctx.body=响应;}elseif(mock){//有值returnctx.body=mock;}}赶上(错误){ctx.status=500;returnctx.body={error,msg:'Mock函数执行错误'}}//找不到mock函数,然后nextnext();})//底线app.use(asyncctx=>{lethtml=`
