運行
$ npx express-generator api-server
創(chuàng)建一個express項目$ cd api-server
進入項目目錄$ npm install
安裝項目所需要的依賴$ npm install nodemon -D
安裝nodemon$ npm install mockjs -S
安裝mockjs包打開項目目錄下的
package.json
, 更改scripts
:
// 引入express
const express = require('express');
// 只使用router
const router = express.Router();
// 引入Mock對象
const Mock = require('mockjs')
// 定義生成數(shù)據(jù)列表的方法
const generateData = () => {
// 使用Mock.mock方法來生成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)"
}
]
})
}
// 定義另外一個方法响疚,用于生成單個數(shù)據(jù)
const generateDataById = (id) => {
return Mock.mock({
"code": 200,
data: {
id,
"title": "@ctitle(15, 25)",
"author": "@cname",
"volume": "@int(100, 300)",
"createAt": "@int(10000000000000, 1554363040517)"
}
})
}
/* 獲取用戶列表 */
router.get('/', function(req, res, next) {
res.json(generateData())
});
/* 獲取單個用戶,根據(jù)用戶的id, 這里有一個express通配符路由(動態(tài)路由) */
router.get('/:id', function(req, res, next) {
const {
id
} = req.params
res.json(generateDataById(id))
});
module.exports = router;
根據(jù)需要配置路由
比如背犯,有一個叫users的路由掛載在
/api/v1/users
下柳琢,就可以這么來寫這個mock數(shù)據(jù)
<pre spellcheck="false" class="md-fences md-end-block ty-contain-cm modeLoaded" lang="js" cid="n20" mdtype="fences"
style="box-sizing: border-box; overflow: visible; font-family: var(--monospace); font-size: 0.9em; display: block; break-inside: avoid; text-align: left; white-space: normal; background-image: inherit; background-position: inherit; background-size: inherit; background-repeat: inherit; background-attachment: inherit; background-origin: inherit; background-clip: inherit; background-color: rgb(248, 248, 248); position: relative !important; border: 1px solid rgb(231, 234, 237); border-radius: 3px; padding: 8px 4px 6px; margin-bottom: 15px; margin-top: 15px; width: inherit;">// 引入express
const express = require('express');
// 只使用router
const router = express.Router();
// 引入Mock對象
const Mock = require('mockjs')
?
?
// 定義生成數(shù)據(jù)列表的方法
const generateData = () => {
// 使用Mock.mock方法來生成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)"
}
]
})
}
?
// 定義另外一個方法绍妨,用于生成單個數(shù)據(jù)
const generateDataById = (id) => {
return Mock.mock({
"code": 200,
data: {
id,
"title": "@ctitle(15, 25)",
"author": "@cname",
"volume": "@int(100, 300)",
"createAt": "@int(10000000000000, 1554363040517)"
}
})
}
/* 獲取用戶列表 */
router.get('/', function(req, res, next) {
res.json(generateData())
});
/* 獲取單個用戶,根據(jù)用戶的id, 這里有一個express通配符路由(動態(tài)路由) */
router.get('/:id', function(req, res, next) {
const {
id
} = req.params
res.json(generateDataById(id))
});
?
module.exports = router;
?</pre>
這樣我們就可以使用 http://localhost:port/users
獲取用戶列表, 使用 http://localhost:port/users/任意的id參數(shù)
獲取用戶信息
*更改于 2019-04-18 *