1.安装mock.js
npm i mockjs --save-dev
2.在src同级目录添加mock-server文件夹内涵3个文件如下
index.js //假接口入口配置文件
userInfo.json //接口demo json 详细看mockjs文档
util.js //读取json配置
3.在webpack.dev.conf.js内配置
devServer:{
proxy: config.dev.proxyTable,//参照位置
...
before: require('../mock-server'), //添加
...
}
4.utils
const fs = require('fs');
const path = require('path');
module.exports = {
//读取json文件
getJsonFile: function (filePath) {
var json = fs.readFileSync(path.resolve(__dirname, filePath), 'utf-8');
return JSON.parse(json);
}
};
5.index.js
const Mock = require('mockjs');
const util = require('./util');
module.exports = function (app) {
//获取用户信息
app.get('/user/userinfo', function (rep, res) {
var json = util.getJsonFile('./userInfo.json');
res.json(Mock.mock(json));
});
//登录
app.post('/login', function (rep, res) {
var json = util.getJsonFile('./userInfo.json');
res.json(Mock.mock(json));
});
}
userInfo.json
{
"error": 0,
"data": {
"userid": "@id()",
"username": "@cname()",
"date": "@date()",
"avatar": "@image('200x200','red','#fff','avatar')",
"description": "@paragraph()",
"ip": "@ip()",
"email": "@email()"
}
}
4、接口请求和index.js里的本地接口路径一致,这样请求的时候就会拦截成本地json内的内容。