这里需要用到json-server和mockjs模拟插件。
json-server: https://github.com/typicode/json-server
mockjs: http://mockjs.com/
npm install json-server –save-dev
npm install mockjs –save-dev
// mock框架,这里demo暂时没用到
var Mock = require('mockjs');
var apiUser = require('./modules/user.js');
var apiGoods = require('./modules/goods.js');
module.exports = {
login: apiUser.login,
goodsList: apiGoods.goodsList
}
const routes = {
"/user/login": "/login",
"/goods/list": "/goodsList"
}
module.exports = routes;
const jsonServer = require('json-server');
const db = require('./db.js');
const routes = require('./routes.js');
const port = 3000;
const server = jsonServer.create()
const router = jsonServer.router(db)
const middlewares = jsonServer.defaults()
const rewriter = jsonServer.rewriter(routes)
server.use(middlewares)
// 将 POST 请求转为 GET
server.use((request, res, next) => {
request.method = 'GET';
next();
});
server.use(rewriter) // 注意:rewriter 的设置一定要在 router 设置之前
server.use(router)
server.listen(port, () => {
console.log(`open mock server at http://localhost:${port}`);
})
function login(config) {
// 模拟数据
let result = {
code: 200,
data: null,
msg: '获取成功',
time: new Date()
}
result.data = { userName: "hello", mobile: "13888888888" };
return result;
}
module.exports = {
login: login()
}
function goodsList(config) {
// 模拟数据
let result = {
"status": "0",
"result": [
{
"productId": "10001",
"productName": "小米6",
"prodcutPrice": "2499",
"prodcutImg": "mi6.jpg"
},
{
"productId": "10002",
"productName": "小米笔记本",
"prodcutPrice": "3999",
"prodcutImg": "minote.jpg"
}
]
};
return result;
}
module.exports = {
goodsList: goodsList()
}
在/config/index.js中添加如下
module.exports = {
dev: {
proxyTable: {
'/mock': {
target: 'http://localhost:3000', // 需要请求的地址
changeOrigin: true, // 是否跨域
pathRewrite: {
'^/mock': '/' // 替换target中的请求地址,例如请求的时候把'/login'换成'/mock/login'
}
},
}
}
这里由于涉及到一个终端开启两个端口的服务,所以需要用到concurrently,先安装concurrently。
npm install concurrently –save-dev
在package.json中添加如下脚本
"scripts": {
"dev": "webpack-dev-server --inline --progress --config build/webpack.dev.conf.js",
"start": "npm run dev",
"build": "node build/build.js",
"mock-server": "node ./src/mock/server.js",
"mock-dev": "concurrently \"npm run dev\" \"npm run mock-server\""
},
npm run mock-dev
运行成功后就可以请求模拟数据了。
接口请求地址
http://localhost:3000/login
http://localhost:3000/goodsList
本人也是第一次使用json-server和mockjs来模拟数据,有问题再记录。