mock-middleware
前端工程处理 mock 数据中间件
介绍
工作图
用法
mock 目录建立与服务地址对应,如/api/user -> mock/api/user.js
npm i -D mock-middleware
require('webpack-mock-middleware')
webpack before
const isMock = process.env.npm_config_mock;
const eMock = require('./e-mock-middle.js');
module.exports = app => {
if (isMock) {
app.all("/api/*", function(req, res, next) {
eMock(req, res, next);
});
}
};
const mockProxy = require('mock.js');
{
devServer: {
before: mockProxy,
}
}
Demo
vue cli3 构建项目
下面是工程目录
工程目录
|--mock
|--mock.js
|--api
|--user.js
|--queryuser.js
|--vue.config.js
mock 数据示例
数据
module.exports = {
data: [
{
username: 'Eric a',
age: 10000
},
{
username: 'Eric b',
age: 10000
},
{
username: 'Eric c',
age: 10000
}
],
code: 200,
message: '操作成功'
};
动态数据
module.exports = req => {
let query = req.query;
console.log(query);
let data = [
{
id: 1,
name: 'Eric a'
},
{
id: 2,
name: 'Eric b'
}
];
let filterRes = data.filter(itm => itm.id == query.id);
return {
code: 200,
data: filterRes,
message: filterRes.length ? '获取成功' : '暂无数据'
};
};
提供mock.js,接入mock-middleware
准备
{
"scripts": {
"serve": "vue-cli-service serve",
"dev": "npm run serve",
"dev:mock": "npm run dev --mock"
}
}
npm run dev:mock
process.env.npm_config_mock
mock.js接入
const isMock = process.env.npm_config_mock;
const eMock = require('mock-middleware')
module.exports = app => {
if (isMock) {
app.all("/api/*", function(req, res, next) {
eMock(req, res, next);
});
}
};
webpack接入
在这里以vue.config.js示例
const mockProxy = require('mock.js');
{
devServer: {
before: mockProxy,
}
}