From 858b835f367e00788ce09d9ed558d2325c04fe30 Mon Sep 17 00:00:00 2001 From: RoBlues Date: Sun, 2 Feb 2020 13:52:01 +0800 Subject: [PATCH] =?UTF-8?q?modify=20=E6=8A=8Amock/index.js=E4=B8=AD?= =?UTF-8?q?=E4=B8=8Emock-server=E7=9B=B8=E5=85=B3=E7=9A=84=E4=BB=A3?= =?UTF-8?q?=E7=A0=81=E8=BD=AC=E7=A7=BB=E5=88=B0mock-server.js=E4=B8=AD?= =?UTF-8?q?=E5=8E=BB=EF=BC=8C=E5=AE=9E=E7=8E=B0=E4=B8=A4=E5=88=99=E5=8A=9F?= =?UTF-8?q?=E8=83=BD=E5=88=86=E5=89=B2?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- mock/index.js | 16 +--------------- mock/mock-server.js | 31 +++++++++++++++++++++++++++++-- 2 files changed, 30 insertions(+), 17 deletions(-) diff --git a/mock/index.js b/mock/index.js index 217ee3d5..196e2927 100644 --- a/mock/index.js +++ b/mock/index.js @@ -54,18 +54,4 @@ export function mockXHR() { } } -// for mock server -const responseFake = (url, type, respond) => { - return { - url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`), - type: type || 'get', - response(req, res) { - console.log('request invoke:' + req.path) - res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond)) - } - } -} - -export default mocks.map(route => { - return responseFake(route.url, route.type, route.response) -}) +export default mocks diff --git a/mock/mock-server.js b/mock/mock-server.js index 4c4cb2af..873d7bc4 100644 --- a/mock/mock-server.js +++ b/mock/mock-server.js @@ -5,14 +5,30 @@ const path = require('path') const mockDir = path.join(process.cwd(), 'mock') +const Mock = require('mockjs') + +/** + * 修订说明:把mock文件夹下面的文件功能进行梳理 + * + * 1. /mock/index.js输出mockXHR()函数,使用改写 + * XMLHttpRequest对象的方式,在浏览器中拦截请求,返回响应 + * + * 2. /mock/mock-server.js引用/mock/index.js中导出的 + * mocks数据(未经responseFake转换),自行加工后作为 + * devServer启动的express应用的路由,从而实现真正的后台 + * api服务 + */ function registerRoutes(app) { let mockLastIndex const { default: mocks } = require('./index.js') - for (const mock of mocks) { + const mocksForServer = mocks.map(route => { + return responseFake(route.url, route.type, route.response) + }) + for (const mock of mocksForServer) { app[mock.type](mock.url, mock.response) mockLastIndex = app._router.stack.length } - const mockRoutesLength = Object.keys(mocks).length + const mockRoutesLength = Object.keys(mocksForServer).length return { mockRoutesLength: mockRoutesLength, mockStartIndex: mockLastIndex - mockRoutesLength @@ -27,6 +43,17 @@ function unregisterRoutes() { }) } +// for mock server +const responseFake = (url, type, respond) => { + return { + url: new RegExp(`${process.env.VUE_APP_BASE_API}${url}`), + type: type || 'get', + response(req, res) { + console.log('request invoke:' + req.path) + res.json(Mock.mock(respond instanceof Function ? respond(req, res) : respond)) + } + } +} module.exports = app => { // es6 polyfill require('@babel/register')