適合人群:初學(xué)者
- 運(yùn)行
$ npx express-generator api-server創(chuàng)建一個(gè)express項(xiàng)目
-
$ cd api-server進(jìn)入項(xiàng)目目錄
-
$npm i安裝項(xiàng)目需要的依賴包
-
$npm i nodemon -D安裝nodemon
-
$npm i mockjs -S安裝mockjs包
- 打開項(xiàng)目目錄下的
package.json, 更改scripts:
改前 "start": "node ./bin/www"
改后 "start": "nodemon ./bin/www"
- 根據(jù)需要配置路由
- 比如,有一個(gè)叫users的路由掛載在
/api/v1/users下,就可以這么來(lái)寫這個(gè)mock數(shù)據(jù)
// 引入express
const express = require('express');
// 只使用router
const router = express.Router();
// 引入Mock對(duì)象
const Mock = require('mockjs')
// 定義生成數(shù)據(jù)列表的方法
---這里是方法代碼塊---
方法 一
方法 二
方法 三
module.exports = router;
一:定義生成數(shù)據(jù) 普通 列表的方法
const generateData = () => {
// 使用Mock.mock方法來(lái)生成mock數(shù)據(jù)
return Mock.mock({
"code": 200,
"data|12": [
{
"id": "@id",
"title": "@ctitle(15, 25)",
"author": "@cname",
"volume": "@int(100, 300)",
"createAt": "@int(10000000000000, 1554363040517)"
}
]
})
}
/* 獲取用戶列表方式 */
router.get('/', function(req, res, next) {
res.json(generateData())
});
二:定義生成數(shù)據(jù) 攜帶id 請(qǐng)求單條數(shù)據(jù)的方法
// 定義另外一個(gè)方法,用于生成單個(gè)數(shù)據(jù)
const generateDataById = (id) => {
return Mock.mock({
"code": 200,
data: {
id, //請(qǐng)求ID
"title": "@ctitle(15, 25)",
"author": "@cname",
"volume": "@int(100, 300)",
"createAt": "@int(10000000000000, 1554363040517)"
}
})
}
/* 獲取單個(gè)用戶,根據(jù)用戶的id, 這里有一個(gè)express通配符路由(動(dòng)態(tài)路由) */
//這里 '/:id'中 ‘:’是通配符的意思
router.get('/:id', function(req, res, next) {
const { id } = req.params
res.json(generateDataById(id))
});
三:定義生成數(shù)據(jù) 限定頁(yè)數(shù)條數(shù) 列表的方法
//生成限定第幾頁(yè)數(shù)據(jù)
const generateDataPage=(limited=10 , offset=0)=>{
return Mock.mock({
code: 200,
data:{
currentPage: (offset / limited) + 1 , //計(jì)算第幾頁(yè)公式
isLastPage:false,//是否最后一頁(yè),否
total:1000, //這里寫多少可以,實(shí)際開發(fā)中以后端為主
//特別注意這里 [`list|${limited}`]模板字符串,變量key用括號(hào)包起來(lái)
[`list|${limited}`]: [
{
"id": "@id",
"img": "@img(262x262,@color)",
"title": "@ctitle(8,12)",
"price|1-1000": 20,
"status": "@ctitle(2)"
}
]
}
})
}
//生成指定的第幾頁(yè)數(shù)據(jù)
router.get('/pages', function(req, res, next) {
//解構(gòu)
const {limited=5, offset=0} = req.query
//請(qǐng)求的參數(shù),一次limited條
res.json(generateDataPage(limited,offset))
});
以上代碼為完整代碼,只是拆開解析,方便理解,主要放進(jìn)相應(yīng)位置即可。寫的不足的地方,還請(qǐng)指教!