title: mockjs + json-server 搭建mock服務(wù)
date: '2021-10-18'
categories:
- JS
tags: - mock
publish: true
:::tip
前后端分離情況下,后端未開發(fā)完成橱鹏,前端使用mock自行模擬數(shù)據(jù)。
:::
// 目錄結(jié)構(gòu)
|-- mockServer
|-- mock
|-- db.json
|-- index.js
|-- middleware.js
|-- package.json
一、安裝
npm i mockjs json-server nodemon cross-env glob -S
// package.json
"scripts": {
"mock:server": "cross-env nodemon index.js --watch 'mock' --watch './middleware.js'"
},
二辱匿、使用
// index.js
const path = require('path');
const fs = require('fs');
const jsonServer = require('json-server');
const mockJs = require('mockjs');
const Random = mockJs.Random;
const customMiddleware = require('./middleware');
const glob = require('glob');
const server = jsonServer.create();
const middlewares = jsonServer.defaults();
// mock數(shù)據(jù)趟脂,常駐內(nèi)存
let data = {}
/**
* mock解析json文件
* @param file
* @returns {*}
*/
function parsingToMockJs(file) {
const json = fs.readFileSync(file, 'utf-8');
return mockJs.mock(JSON.parse(json));
}
/**
* 合并json數(shù)據(jù)
* @param path
*/
function mergeJsonData(path) {
Object.assign(data, parsingToMockJs(path));
}
/**
* 掃描mock目錄励稳,生成mock數(shù)據(jù)
*/
glob(path.join(__dirname, `/mock/*.json`), {}, (err, files) => {
files.forEach(item => {
mergeJsonData(item);
});
const router = jsonServer.router(data);
// 自定義路由
server.post('/api/upload/image', (req, res) => {
res.jsonp({
id: Random.image('300x250', Random.color())
});
})
server.use(jsonServer.bodyParser);
server.use(middlewares);
// 添加響應(yīng)頭
server.use((req, res, next) => {
res.header('author', 'Ice');
next();
});
server.use(customMiddleware);
// 數(shù)據(jù)統(tǒng)一封裝
router.render = (req, res) => {
res.jsonp({
success: true,
code: 0,
msg: 'success',
data: res.locals.data
});
}
server.use('/api', router);
server.listen(3000, () => {
console.log('Mock server is running......')
});
});
// middleware.js
const mockJs = require('mockjs');
const Random = mockJs.Random;
module.exports = (req, res, next) => {
// 可以對請求進(jìn)行特殊操作
console.log(req.body);
console.log(req._parsedUrl);
if(req.method === 'POST' && req._parsedUrl.pathname === '/api/dynamics') {
req.body.imageUrl = Random.image('300x250', Random.color());
req.body.viewCount = Random.natural(1, 1000);
}
next()
}
// 啟動
npm run mock:server
-
1、分頁列表請求
-
數(shù)據(jù)
// db.json // 一百條數(shù)據(jù) { "dynamics|100": [ { "id|+1": 1, "title": "@cparagraph()", "imageUrl": "@image", "viewCount": "@natural(1, 1000)" } ] }
-
請求
GET: http://localhost:3000/api/dynamics?_page=1&_limit=20
-
-
2凳谦、刪除一條數(shù)據(jù)
數(shù)據(jù)同1
-
請求
// 刪除第一條 DELETE: http://localhost:3000/api/dynamics/1
-
3、獲取一條數(shù)據(jù)
- 數(shù)據(jù)同1
- 請求
// 獲取第一條 GET: http://localhost:3000/api/dynamics/1
-
4衡未、修改一條數(shù)據(jù)
數(shù)據(jù)同1
-
請求
// 修改第一條 PATCH: http://localhost:3000/api/dynamics/1 data: { title: 'xxx' }
-
5尸执、添加一條數(shù)據(jù)
- 數(shù)據(jù)同1
- 請求
// 修改第一條 POST: http://localhost:3000/api/dynamics data: { title: 'xxx' }
6家凯、上傳圖片
自定義路由在 server.use(jsonServer.bodyParser);
之前。
// 自定義路由
server.post('/api/upload/image', (req, res) => {
// 這里還是不使用真實上傳的圖片
res.jsonp({
id: Random.image('300x250', Random.color())
});
})