1.前言
在前後端分離開發過程中,爲了避免前端開發完成而後端接口還未跟上進度時,往往會用mock來模擬接口數據。可以選擇用第三方mock平臺,也可以選擇自己搭建mock服務。這裏我將給出一個簡易的mock restful api服務源代碼(node.js實現)。
更多mock相關內容參考mock.js官方http://mockjs.com/
2.代碼實現
2.1 目錄結構
2.2 包依賴:package.json
{
"name": "mock-server",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"express": "^4.16.4",
"mockjs": "^1.0.1-beta3",
"nodemon": "^1.18.10"
}
}
2.3 mock-server.js代碼部分(服務器主要邏輯)
const path = require('path') // 引入path模塊
const fs = require('fs') // 引入fs模塊
const express = require('express') // 引入express模塊
const bodyParser = require('body-parser') // body-parser中間件解析post請求
const app = express() // 實例化express
const mockData = {} // mock數據
// www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}))
// // application/json
// app.use(bodyParser.json());
// 判斷是否是文件夾
function isFileExists (filePath) {
const stat = fs.lstatSync(filePath)
return stat.isDirectory()
}
// 讀取mock目錄下的所有文件,組裝mockData
function readMockDir (dir) {
fs.readdirSync(dir).forEach(function (file) {
let _path = path.join(dir + '/' + file)
if (isFileExists(_path)) {
readMockDir(_path)
} else {
Object.assign(mockData, require(_path))
}
})
}
readMockDir(path.join(__dirname + '/mock'))
// 遍歷mockData對象,
// 獲取每個接口的路徑(url)和方法(method),
// 並通過express調用mock數據
for (let key in mockData) {
let _key = key.replace(/(^\s*)|(\s*$)/g, '')
let _method = 'get'
let _url = _key.replace(/^(get|post|put|delete)\s*/i, function (rs, $1) {
_method = $1.toLowerCase()
return ''
})
app[_method](_url, mockData[key])
}
// 監聽8090端口
app.listen('8090', function () {
console.log('MOCK Server is running at http://localhost:8090')
})
2.4 mock-start.js(入口,開啓守護進程)
const path = require('path') // 引入path模塊
const fs = require('fs') // 引入fs模塊
const express = require('express') // 引入express模塊
const bodyParser = require('body-parser') // body-parser中間件解析post請求
const app = express() // 實例化express
const mockData = {} // mock數據
// www-form-urlencoded
app.use(bodyParser.urlencoded({
extended: true
}))
// // application/json
// app.use(bodyParser.json());
// 判斷是否是文件夾
function isFileExists (filePath) {
const stat = fs.lstatSync(filePath)
return stat.isDirectory()
}
// 讀取mock目錄下的所有文件,組裝mockData
function readMockDir (dir) {
fs.readdirSync(dir).forEach(function (file) {
let _path = path.join(dir + '/' + file)
if (isFileExists(_path)) {
readMockDir(_path)
} else {
Object.assign(mockData, require(_path))
}
})
}
readMockDir(path.join(__dirname + '/mock'))
// 遍歷mockData對象,
// 獲取每個接口的路徑(url)和方法(method),
// 並通過express調用mock數據
for (let key in mockData) {
let _key = key.replace(/(^\s*)|(\s*$)/g, '')
let _method = 'get'
let _url = _key.replace(/^(get|post|put|delete)\s*/i, function (rs, $1) {
_method = $1.toLowerCase()
return ''
})
app[_method](_url, mockData[key])
}
// 監聽8090端口
app.listen('8090', function () {
console.log('MOCK Server is running at http://localhost:8090')
})
2.5 一個測試實例
mock/api1/api1.js
const Mock = require('mockjs')
let getApi1Data = (req) => {
// console.log(req.query);
return Mock.mock({
'data|1-9': [{
'name|5-8': /[a-zA-Z]/,
'id|+1': 1,
'value|0-500': 0,
'age|1-100': 1
}]
})
}
module.exports = {
[`GET /api1`] (req, res) {
res.status(200).json(getApi1Data(req))
}
}
2.6 啓動命令
(在mock-server目錄下)
npm install (安裝依賴)
node mock-start.js (開啓服務)