mock基础版本需要通过before实现
before: require('./mock'),//引入mock/index.js
mock+express
废话不多说线上代码
pm i express -D
npm i mockjs -D
express了解连接 https://www.expressjs.com.cn/starter/hello-world.html
新建
api文件 放接口路由配置
data 文件夹放json数据
新建mock-serve.js 启动文件
list.js
const express = require('express')
const listRoutes = express.Router() // 定义接口路由
// json 方式
//const user_list = require('../data/user_list.json')
// 函数方式数据
const data = require('../data/db.js')
listRoutes.get('/user/list', function (req, res) {
res.json({
code: 200,
//json方式调用
// data: user_list
data: data.user_list()
})
})
listRoutes.get('/article/list', function (req, res) {
res.json({
code: 200,
data: data.article_list()
})
})
module.exports = listRoutes
db.js / user_list.json 这两个文件都是数据文件 只是取数据方式不一样 ,db是我自己相处的方法,因为写json文件太麻烦后期也会越写越多
db.js
module.exports = {
'user_list': function (){
const data = {
"error":200,
"data":[
{
"userid": "111",
"username": "test",
"date": "2222.12.29"
},
{
"userid": "111",
"username": "test",
"date": "2222.12.29"
}
]
}
return JSON.stringify(data)
},
'article_list': () => {
const data = {
"error":200,
"data":[
{
"userid": "111",
"username": "test",
"date": "2222.12.29"
},
{
"userid": "111",
"username": "test",
"date": "2222.12.29"
}
]
}
return JSON.stringify(data)
}
}
user_list.json
{
"error":500,
"data":[
{
"userid": "111",
"username": "test",
"date": "2222.12.29"
},
{
"userid": "111",
"username": "test",
"date": "2222.12.29"
}
]
}
主角mock-serve.js
const express = require('express')
const app = express()
const port = 3000
const listRoutes = require('./api/list')
console.log('listRoutes',listRoutes)
app.use('/api', listRoutes)
app.listen(port, () => {
console.log('===========》启动mock模拟数据《===========')
console.log(`访问路径 http://localhost:${port}`)
})
启动
node mock/mock-serve.js
本地开发访问配置代理
const devServerPort = 9527 // TODO: get this variable from setting.ts
const mockServerPort = 3000
module.exports = {
devServer: {
port: devServerPort,
open: true,
overlay: {
warnings: false,
errors: true
},
progress: false,
proxy: {
// change xxx-api/login => /mock-api/v1/login
// detail: https://cli.vuejs.org/config/#devserver-proxy
'/api': {
target: `http://localhost:${mockServerPort}`,
changeOrigin: true, // needed for virtual hosted sites
ws: true, // proxy websockets
pathRewrite: {
['^ api' ]: ''
}
}
}
}
}
页面访问
created() {
axios('/api/user/list', { params: {username: 'test'} }).then(res => {
console.log(res);
this.username = res.username;
})
}