mock数据是前端比较常见的技术,这里介绍下vue配合express 实现请求数据mock。
第一步:
安装 express : npm install express -D
第二步:
简历需要mock的数据,在src下新建mock文件夹,文件里面新建两个文件data1.json和data2.json,如下:
data1.json内容如下:
{
"name": "yanyalong",
"title": "测试",
"data": [
{
"field_code": "111", "code": "initiatorDept", "errcode": 0, "errmsg": "ok","mextendData": null, "formId": "processVariable", "formName": "流程字段11", "id": "initiatorDept", "name": "stringsasassa", "system": true,
"type" : { "errcode" : 0,"errmsg" : "ok","id" : null, "code" : null,"name" : "string" },
"relationListType": ["equals","containsIgnoreCase"]
},
{
"field_code": "22", "code": "initiatorDept", "errcode": 0, "errmsg": "ok","mextendData": null, "formId": "processVariable", "formName": "流程字段11", "id": "asdada", "name": "发起人部门", "system": true,
"type" : { "errcode" : 0,"errmsg" : "ok","id" : null, "code" : null,"name" : "reference" },
"relationListType": ["contains","stringNotContains"]
},
{
"field_code" : "33", "errcode" : 0, "errmsg" : "ok","id" : "initiatorUserGroup", "code" : "initiatorUserGroup", "name" : "发起人所属用户组","system" : true,
"type" : {"errcode" : 0,"errmsg" : "ok", "id" : null, "code" : null, "name" : "string" }, "formId" : "processVariable","formName" : "流程字段","extendData" : null,
"relationListType": ["notEquals","containsIgnoreCase", "notContainsIgnoreCase"]
}
]
}
data2.json内容如下:
{
"value": "hello 你好"
}
第三步:
修改 webpack.dev.conf.js 的配置,在devServer里新增如下代码,这样在请求/api1 这个url路径的时候就会返回data1.json, /api2返回data2.json
before (app) {
const express = require('express')
const App = express()
// 加载本地数据文件
var appData1 = require('./../src/mock/data1.json')
var appData2 = require('./../src/mock/data2.json')
var apiRoutes = express.Router()
App.use('/api1', apiRoutes)
App.use('/api2', apiRoutes)
app.get('/api1', (req, res) => {
res.json(appData1)
})
app.get('/api2', (req, res) => {
res.json(appData2)
})
}
第四步:
使用方法如下:
<template> <div id="app"> <img src="./assets/logo.png"> <HelloWorld/> </div> </template> <script> import axios from 'axios' import HelloWorld from './components/HelloWorld' export default { name: 'App', components: { HelloWorld }, mounted () { axios.get('/api1').then((res) => { console.log(res) }) axios.get('/api2').then((res) => { console.log(res) }) } } </script>
具体的代码可以看这里:https://github.com/YalongYan/vue-practice/tree/master/express-axios-mock
补充说明:
现在的vue-cli项目没有了webpack.dev.conf.js文件了,不过有webpack.config.js, 原理是一样的,在webpack.config.js里面找到devServer, 把 before (app) 这段代码放进去效果是一样的。
我这里做了判断,只有开发环境的时候 才启用mock请求数据,生产环境的时候就不需要了,代码如下(这段代码是在webpack.dev.conf.js最后面):
if (process.env.NODE_ENV === 'production') {
// 生产环境的代码
} else {
// express 实现 mock数据
module.exports.devServer.before = (app)=> {
const express = require('express')
const App = express()
// 加载本地数据文件
var appData = require('./src/mock/data1.json')
var apiRoutes = express.Router()
App.use('/api', apiRoutes)
app.get('/api', (req, res) => {
res.json(appData)
})
}
}