前言:官网描述
1.前后端分离
2.不需要修改既有代码,就可以拦截 Ajax 请求,返回模拟的响应数据。
3.数据类型丰富
4.通过随机数据,模拟各种场景。
其实就是在后端接口开发完成之前,我们前端可以用已有的接口文档,在真实的请求上拦截ajax,根据mockjs的mock数据的规则模拟真实接口返回的数据,并将模拟数据返回参与相应的数据交互处理,这样真正实现了前后台的分离开发。
与以往模拟的假数据不同,mockjs可以带给我们的是:在后台接口未开发完成之前模拟数据并返回,完成前台的交互;在后台数据完成之后,你所做的只是去掉mockjs:停止拦截真实的ajax,仅此而已。
接下来就一步一步实现这个过程:
- 引入mockjs依赖
npm install mockjs --save-dev
-
建一个mock文件夹统一管理mock数据
3.在mock文件夹下建一个index.js(写关键代码,拦截到我们前端发出的请求)
const Mock = require('mockjs')
// 解析地址栏参数的函数
const { param2Obj } = require('./utils')
// 导入模拟数据
const user = require('./user')
const role = require('./role')
const list = require('./list')
const mocks = [
...user,
...role,
...list
]
// for front mock
// please use it cautiously, it will redefine XMLHttpRequest,
// which will cause many of your third-party libraries to be invalidated(like progress event).
function mockXHR() {
// mock patch
// https://github.com/nuysoft/Mock/issues/300
Mock.XHR.prototype.proxy_send = Mock.XHR.prototype.send
Mock.XHR.prototype.send = function() {
if (this.custom.xhr) {
this.custom.xhr.withCredentials = this.withCredentials || false
if (this.responseType) {
this.custom.xhr.responseType = this.responseType
}
}
this.proxy_send(...arguments)
}
function XHR2ExpressReqWrap(respond) {
return function(options) {
let result = null
if (respond instanceof Function) {
const { body, type, url } = options
// https://expressjs.com/en/4x/api.html#req
result = respond({
method: type,
body: JSON.parse(body),
query: param2Obj(url)
})
} else {
result = respond
}
return Mock.mock(result)
}
}
// 批量注册路由事件
for (const i of mocks) {
Mock.mock(new RegExp(i.url), i.type || 'get', XHR2ExpressReqWrap(i.response))
}
}
module.exports = {
mocks,
mockXHR
}
- mock文件夹下新建utile.js文件
/**
* @param {string} url
* @returns {Object}
*/
function param2Obj(url) {
const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
if (!search) {
return {}
}
const obj = {}
const searchArr = search.split('&')
searchArr.forEach(v => {
const index = v.indexOf('=')
if (index !== -1) {
const name = v.substring(0, index)
const val = v.substring(index + 1, v.length)
obj[name] = val
}
})
return obj
}
/**
* This is just a simple version of deep copy
* Has a lot of edge cases bug
* If you want to use a perfect deep copy, use lodash's _.cloneDeep
* @param {Object} source
* @returns {Object}
*/
function deepClone(source) {
if (!source && typeof source !== 'object') {
throw new Error('error arguments', 'deepClone')
}
const targetObj = source.constructor === Array ? [] : {}
Object.keys(source).forEach(keys => {
if (source[keys] && typeof source[keys] === 'object') {
targetObj[keys] = deepClone(source[keys])
} else {
targetObj[keys] = source[keys]
}
})
return targetObj
}
module.exports = {
param2Obj,
deepClone
}
- main.js文件中引入
// main.js 开启mock 服务
import { mockXHR } from '../mock'
if (process.env.NODE_ENV === 'development') {
mockXHR()
}
6.下面封装有两种封装使用方式
一、
(1)mock文件夹中新增mock-server.js文件封装请求
下载安装 chokidar、body-parser、chalk、path
chokidar(监听文件变化):
npm install --save-dev chokidar
body-parser(配合post 通过req.body获取前端的请求数据):
npm install --save-dev express ejs body-parser
chalk(命令行颜色的插件):
npm install --save-dev chalk
const chokidar = require('chokidar')
const bodyParser = require('body-parser')
const chalk = require('chalk')
const path = require('path')
const Mock = require('mockjs')
// path模块是node.js中处理路径的核心模块。可以很方便的处理关于文件路径的问题。
// join() 将多个参数值合并成一个路径
const mockDir = path.join(process.cwd(), 'mock')
function registerRoutes(app) {
let mockLastIndex
const { mocks } = require('./index.js')
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(mocksForServer).length
return {
mockRoutesLength: mockRoutesLength,
mockStartIndex: mockLastIndex - mockRoutesLength
}
}
function unregisterRoutes() {
Object.keys(require.cache).forEach(i => {
if (i.includes(mockDir)) {
delete require.cache[require.resolve(i)]
}
})
}
// 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 => {
// parse app.body
// https://expressjs.com/en/4x/api.html#req.body
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({
extended: true
}))
const mockRoutes = registerRoutes(app)
var mockRoutesLength = mockRoutes.mockRoutesLength
var mockStartIndex = mockRoutes.mockStartIndex
// watch files, hot reload mock server
chokidar.watch(mockDir, {
ignored: /mock-server/,
ignoreInitial: true
}).on('all', (event, path) => {
if (event === 'change' || event === 'add') {
try {
// remove mock routes stack
app._router.stack.splice(mockStartIndex, mockRoutesLength)
// clear routes cache
unregisterRoutes()
const mockRoutes = registerRoutes(app)
mockRoutesLength = mockRoutes.mockRoutesLength
mockStartIndex = mockRoutes.mockStartIndex
console.log(chalk.magentaBright(`\n > Mock Server hot reload success! changed ${path}`))
} catch (error) {
console.log(chalk.redBright(error))
}
}
})
}
(2)mockjs文件夹下新建几个模拟数据文件(list.js)
// import Mock from 'mockjs'
const Mock = require('mockjs')
const List = []
const count = 50
for (let i = 0; i < count; i++) {
List.push(Mock.mock({
id: '@increment',
'date': '@date("yyyy-MM-dd")',
'name': '@cname',
'province': '@province',
'city': '@city',
'address': '@county(true)',
'postcode': '@zip'
}))
}
module.exports = [
{
url: '/vue-element-admin/commonList/getList',
type: 'get',
response: config => {
var { name, page, limit } = config.query
var mocklist = List.filter(item => {
if (name && item.name.indexOf(name) < 0) return false
return true
})
page = Number(page)
limit = Number(limit)
var newDataList = mocklist.slice((page - 1) * limit, page * limit)
return {
code: 20000,
data: {
page: page,
limit: limit,
total: List.length,
rows: newDataList
}
}
}
}
]
(3) 使用
getList(){
axios.get('/vue-element-admin/commonList/getList',{
params:{
page:1,
limit: 20
}
}).then(function(res){
this.goodsList = res.data.rows;
}).catch(function (error) {
console.log(error);
});
}
二、
(1)封装请求方法
import axios from "axios";
import { Loading, Message } from "element-ui";
import store from "@/store";
// import { getToken } from "@/utils/auth";
// create an axios instance
const service = axios.create({
// baseURL: "",
timeout: 10000, // request timeout
// headers: {
// "Content-Type": "multipart/form-data",
// },
});
let apiCallNo = 0;
let loadingInstance;
// request interceptor
// TODO 待优化
service.interceptors.request.use(
(config) => {
if (config.data) {
const { hideLoading, ...rest } = config.data;
if (!hideLoading) {
apiCallNo += 1;
if (apiCallNo === 1) {
loadingInstance = Loading.service();
}
}
if (Object.keys(rest).length !== 0) {
config.data = rest;
} else if (typeof hideLoading === "boolean") {
config.data = null;
}
} else {
apiCallNo += 1;
if (apiCallNo === 1) {
loadingInstance = Loading.service();
}
}
if (store.getters.token) {
// let each request carry token
// ['X-Token'] is a custom headers key
// please modify it according to the actual situation
// config.headers["X-Token"] = getToken();
}
return config;
},
(error) => {
// do something with request error
return Promise.reject(error);
}
);
// response interceptor
service.interceptors.response.use(
/**
* If you want to get http information such as headers or status
* Please return response => response
*/
/**
* Determine the request status by custom code
* Here is just an example
* You can also judge the status by HTTP Status Code
*/
(response) => {
apiCallNo -= 1;
if (apiCallNo === 0) {
loadingInstance.close();
}
const res = response.data;
// 导出二进制流数据
if (res.type) {
return res;
}
// 普通请求
if (res.status !== 200) {
Message({
message: res.message || "Error",
type: "error",
duration: 5 * 1000,
});
return Promise.reject(new Error(res.message || "Error"));
// 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
// if (res.code === 50008 || res.code === 50012 || res.code === 50014) {
// // to re-login
// MessageBox.confirm(
// "You have been logged out, you can cancel to stay on this page, or log in again",
// "Confirm logout",
// {
// confirmButtonText: "Re-Login",
// cancelButtonText: "Cancel",
// type: "warning",
// }
// ).then(() => {
// store.dispatch("user/resetToken").then(() => {
// location.reload();
// });
// });
// }
} else {
return res.data;
}
},
(error) => {
console.log(error.response);
apiCallNo -= 1;
if (apiCallNo === 0) {
loadingInstance.close();
}
Message({
message: error.response?.data.message ?? "网络异常,请重试", // TODO 是否要改成统一的提示?
type: "error",
duration: 5 * 1000,
});
return Promise.reject(error);
}
);
export default service;
(2)新建一个文件专门封装api
import request from "@/utils/request"; // 引入request方法
// 使用mock模拟后端数据
export function fetchResultTrend(params) {
return request({
url: "/mock/credit-evaluate-statistics/result/trend",
params,
});
}
(3)在vue文件中调用接口
async closerRateChange() {
const res = await fetchResultTrend();
console.log(res)
}
注:
npm / cnpm 下载时代表意义
node :自带的包管理器
install :下载
--save :在package.json中存储为线上需要的插件
--save-dev : 在package.json中存储为线下需要的插件
express :基于node.js 平台,快速、开放、极简的文本开发框架
ejs :通过数据和模板,可以生成HTML标记文本,可以同时运行在客户端和服务器端,0 学习成本
body-parser :配合post 通过req.body获取前端的请求数据
node .\app.js : 开启服务器,链接端口为listen设置的值
注意 :只要更改app.js ,都需要重新开启服务器