- 开启一个服务器(app.js)
const express = require('express')
// 创建服务器
const app = express();
const router = require('./router')
// 允许跨域
app.all('*', function (req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header('Access-Control-Allow-Headers', 'Content-type');
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS,PATCH");
next();
});
app.use(express.static('home'))
// 使用路由模块
app.use(router)
const bodyParser = require('body-parser')
app.use(bodyParser.urlencoded({ extended: false }))
app.listen(3000, () => {
console.log('起飞')
})
- 在router.js文件中设置路由, 并使用mockjs
const express = require('express')
const Mock = require('mockjs')
const getTepmlate = require('./utils')
const router = express.Router()
router.get('/shop', (req, res) => {
let data = getTepmlate({
'name': 'cname',
'id': 'id',
email: 'email'
}, false)
res.send(data)
})
router.get('/new', (req, res) => {
let data = []
for (let index = 0; index < 5; index++) {
let obj = {
'name': Mock.mock('@cname'),
'id': Mock.mock('@id')
}
data.push(obj)
}
const newTemplate = {
code: 0,
msg: 'success',
data: data
}
res.send(newTemplate)
})
// 请求 / 的时候会默认请求home监听资源下的 index.html
router.get('/', (req, res) => {
res.send('hello')
})
module.exports = router
- 封装一个简单的函数, 返回生成的mock数据 (utils.js)
const Mock = require('mockjs')
/**
* 获取模拟数据
* length 需要返回多少条数据,默认随机
*/
function getTepmlate (options = {}, isArrData = true, length) {
let dataLength = Number(length)
// 如果没有传入数据条数,则随机生成
if (!dataLength) {
dataLength = Math.floor(Math.random() * 100)
}
// 获取传入对象的key值, 表示随后生成数据的key
let labelArr = Object.keys(options) || []
// 获取传入对象的value, 表示mock占位符
let valueArr = []
for (const key in options) {
if (Object.hasOwnProperty.call(options, key)) {
valueArr.push(options[key])
}
}
// 返回的数据是数据还是对象
let arrData = []
// 需要返回的数据是数组并且传入的对象中有时
if (isArrData && labelArr.length) {
// 随机遍历, 生成n个数据
for (let index = 0; index < dataLength; index++) {
let obj = {}
// 遍历传入的对象, 生成一组mock数据
for (let index = 0; index < labelArr.length; index++) {
obj[labelArr[index]] = Mock.mock(`@${valueArr[index]}`)
}
arrData.push(obj)
}
}
let objData = {}
// 需要返回的数据是对象并且传入的对象中有时
if (!isArrData && labelArr.length) {
let obj = {}
// 遍历传入的对象, 生成一组mock数据
for (let index = 0; index < labelArr.length; index++) {
obj[labelArr[index]] = Mock.mock(`@${valueArr[index]}`)
}
objData = obj
}
return {
code: 0,
msg: 'success',
data: isArrData ? arrData : objData
}
}
module.exports = getTepmlate