app.js 部分
const jsonServer = require('json-server');//在node里面使用json-server包
const db = require('./db.js');//引入mockjs配置模块
// const multer = reuqire('multer');
const path = require('path');
const Mock = require('mockjs');
let mock='/api';//定义路由根别名
let port = 3333;//端口
//创建服务器
const server = jsonServer.create();//创建jsonserver 服务对象
//配置jsonserver服务器 中间件
server.use(jsonServer.defaults({
// __dirname: 获得当前执行文件所在目录的完整目录名
// path.join() 方法是将多个参数字符串合并成一个路径字符串
static:path.join(__dirname, '/public'),//静态资源托管所在位置
}));
server.use(jsonServer.bodyParser);//抓取body数据使用json-server中间件
// let upload = multer({dest:path.join(__dirname,'public','uploads')});
// server.use(upload.any());
//响应
//可选 统一修改请求方式
server.use((req, res, next) => {
// console.log(1)
// request.method = 'GET';
if (req.url.includes('/login') || req.url.includes('/reg')){
next()
} else {
if (req.headers.token && req.headers.token.length===16){
next()
} else {
setTimeout(()=>res.jsonp({
err:2,
msg:'token无效或过期'
}),1000)
}
}
});
//登录注册校验
let mr = Mock.Random;//提取mock的随机对象
server.post(mock+'/login', (req, res) => {
// console.log(req.query, req.body);//抓取提交过来的query和body
let username=req.body.username;
let password=req.body.password;
(username === 'alex' && password === 'alex123')?
res.jsonp({
"err": 0,
"msg": "登录成功",
"data": {
"follow": mr.integer(1,5),
"fans": mr.integer(1,5),
"nikename": mr.cname(),
"icon": mr.image('20x20',mr.color(),mr.cword(1)),
"time": mr.integer(13,13)
},
"token":mr.integer(16)
}) :
res.jsonp({
"err": 1,
"msg": "登录失败",
})
});
server.post(mock+'/reg', (req, res) => {
let username=req.body.username;
(username !== 'alex') ?
res.jsonp({
"err": 0,
"msg": "注册成功",
"data": {
"follow": mr.integer(0,0),
"fans": mr.integer(0,0),
"nikename": mr.cname(),
"icon": mr.image('20x20',mr.color(),mr.cword(1)),
"time": mr.integer(13,13)
}
}) :
res.jsonp({
"err": 1,
"msg": "注册失败",
})
});
//响应mock接口 自定义返回结构 定义mock接口别名
const router = jsonServer.router(db);//创建路由对象 db为mock接口路由配置 db==object
router.render = (req, res) => {//自定义返回结构
let data = res.locals.data;//object array
// console.log('app.js',res);
let bl = false;
if (typeof data === 'object' && Object.keys(data).length !== 0){
bl = true;
} else {
bl = false; // delete 操作时,返回空对象
}
setTimeout(()=>{//模拟服务器延时
res.jsonp({
err: bl ? 0 : 1,
msg: bl ? '成功' : '失败',
data: res.locals.data
})
},1000)
// res.jsonp(res.locals.data)
};
server.use(jsonServer.rewriter({//路由自定义别名
[mock+"/*"]: "/$1",
// "/product\\?dataName=:dataName": "/:dataName",
// "/banner\\?dataName=:dataName": "/:dataName",
// "/detail\\?dataName=:dataName&id=:id": "/detail/:dataName/:id",
// "/product/del\\?dataName=:dataName&id=:id": "/:dataName/:id",
// "/product/add\\?dataName=:dataName": "/:dataName",
// "/product/check\\?dataName=:dataName&id=:id": "/:dataName/:id"
"/:resource/:id/show": "/:resource/:id",
"/posts/:category": "/posts?category=:category",
"/articles\\?id=:id": "/posts/:id"
}));
server.use(router);//路由响应
//开启jsonserver服务
server.listen(port, () => {
console.log('mock server is running')
});
package.json 部分
{
"name": "cli4",
"version": "0.1.0",
"private": true,
"scripts": {
"serve": "vue-cli-service serve",
"build": "vue-cli-service build",
"mock": "nodemon ./mock/app.js" //引入nodejs
},
"dependencies": {
"axios": "^0.20.0",
"core-js": "^3.6.5",
"vue": "^2.6.11",
"vue-router": "^3.4.3"
},
"devDependencies": {
"@vue/cli-plugin-babel": "^4.5.0",
"@vue/cli-service": "^4.5.0",
"json-server": "^0.16.1",
"mockjs": "^1.1.0",
"vue-template-compiler": "^2.6.11"
}
}
json-server本身就是依赖express开发而来,可以进行深度定制
db.js部分
// 用mockjs模拟生成数据
var Mock = require('mockjs');
// node app.js 要求db.js 暴露一个object
let mapData = (n) => {
let data=[];
for (let i=1; i<=n; i++){
data.push({
_id: i+'',
id: i+'',
title:'@ctitle(8,12)',
des:'@ctitle(10,20)',
time:'@integer(1594004307038,1598004307038)',
detail:{
auth_icon:Mock.Random.image('50x50',Mock.Random.color(),Mock.Random.cword(1)),
auth:'@cname()',
content: [1,2,3].map(()=>(
"
"+"@cparagraph(10,15)"+"
")).join('')
}
})
}
return data;
};
let mapData2 = (n) => {
let data=[];
for (let i=1; i<=n; i++){
data.push({
_id: i+'',
id: i+'',
title:'@ctitle(4,8)',
sub_title:'@ctitle(6,12)',
banner: Mock.Random.image('1680x745',Mock.Random.color(),Mock.Random.cword(4,8)),
time:'@integer(1594004307038,1598004307038)',
detail:{
auth_icon:Mock.Random.image('50x50',Mock.Random.color(),Mock.Random.cword(1)),
auth:'@cname()',
content:'@cparagraph(3)'
}
})
}
return data;
};
module.exports = Mock.mock({
'user': {
"follow":Mock.Random.integer(0,100),
"fans":Mock.Random.integer(0,100),
"nikename":Mock.Random.cname(),
"icon":Mock.Random.image('20x20',Mock.Random.color(),Mock.Random.cword(1)),
"time":Mock.Random.integer(13)
},
'banner':mapData2(10),
'home': mapData(100),
'follow': mapData(80),
'column': mapData(60),
});
/* module.exports = () => {
// 使用 Mock
var data = Mock.mock({
'course|30': [
{
// 属性 id 是一个自增数,起始值为 1,每次增 1
'id|+1': 1000,
course_name: '@ctitle(5,10)',
autor: '@cname',
college: '@ctitle(6)',
'category_Id|1-6': 1
}
],
'course_category|6': [
{
"id|+1": 1,
"pid": -1,
cName: '@ctitle(4)'
}
]
});
// 返回的data会作为json-server的数据
return data;
}; */