為什么使用ta
在項目開發(fā)中徒蟆,常常需要邊寫前端頁面邊寫后端接口狐树,但是后端接口服務(wù)往往是滯后于前端開發(fā)的作谚,或者是不能及時提供的三娩。出于前端開發(fā)的迅速和便捷去考慮,我們可以根據(jù)后端接口數(shù)據(jù)結(jié)構(gòu)去模擬(mock)數(shù)據(jù)從而實現(xiàn)前端的獨(dú)立開發(fā)食磕。
JsonServer 主要的作用就是搭建本地的數(shù)據(jù)接口尽棕,創(chuàng)建json文件,便于調(diào)試調(diào)用
Mockjs 主要的作用就是生成隨機(jī)數(shù)據(jù)彬伦,支持生成隨機(jī)的文本、數(shù)字伊诵、布爾值单绑、日期、郵箱曹宴、鏈接搂橙、圖片、顏色等
如何使用
以下操作需要node.js環(huán)境
1.創(chuàng)建文件夾
選擇自己喜歡的位置創(chuàng)建一個文件夾笛坦,比如E:/mock
2.安裝json-server
進(jìn)入E:/mock
npm install json-server -g
安裝完執(zhí)行 json-server -h区转,若安裝成功則會顯示選項
Options:
--config, -c Path to config file [default: "json-server.json"]
--port, -p Set port [default: 3000]
--host, -H Set host [default: "localhost"]
--watch, -w Watch file(s) [boolean]
--routes, -r Path to routes file
--middlewares, -m Paths to middleware files [array]
--static, -s Set static files directory
--read-only, --ro Allow only GET requests [boolean]
--no-cors, --nc Disable Cross-Origin Resource Sharing [boolean]
--no-gzip, --ng Disable GZIP Content-Encoding [boolean]
--snapshots, -S Set snapshots directory [default: "."]
--delay, -d Add delay to responses (ms)
--id, -i Set database id property (e.g. _id) [default: "id"]
--foreignKeySuffix, --fks Set foreign key suffix (e.g. _id as in post_id)
[default: "Id"]
--quiet, -q Suppress log messages from output [boolean]
--help, -h Show help [boolean]
--version, -v Show version number [boolean]
3.使用json-server
- 創(chuàng)建json文件,如db.json版扩,文件內(nèi)容如下
{
"posts": [
{
"id": 1,
"title": "json-server",
"author": "typicode"
}
],
"comments": [
{
"id": 1,
"body": "some comment",
"postId": 1
}
],
"profile": {
"name": "typicode"
}
}
- 啟動json-server废离,cmd執(zhí)行
json-server --watch db.json
看到如下內(nèi)容
則運(yùn)行成功,直接訪問圖中顯示的三個地址可得結(jié)果礁芦,如
至此蜻韭,簡單的json-server服務(wù)已經(jīng)搭建成功了,后續(xù)如果有更多需求柿扣,如跨域肖方、參數(shù)查詢、路由這些未状,請參考json-server的github
4.安裝Mockjs
進(jìn)入E:/mock
npm install mockjs --save
5.使用Mockjs
- 創(chuàng)建js文件俯画,如news.js,文件內(nèi)容如下
let Mock=require('mockjs');
let Random=Mock.Random;
module.exports=()=>{
let data={
news:[]
};
let images=[1,2,3].map(x=>Random.image('120x60',Random.color(),Random.word(2,6)));
for(let i=1;i<=100;i++){
let content=Random.cparagraph(0,10);
data.news.push({
id:i,
title:Random.cword(8,20),
desc:content.substr(0,40),
tag:Random.cword(2,6),
views:Random.integer(100,5000),
images:images.slice(0,Random.integer(1,3))
})
}
return data
}
- 啟動json-server司草,cmd執(zhí)行
json-server --watch news.js
訪問結(jié)果(部分)
完成了以上的搭建與驗證過程后艰垂,你就可以開始使用json-server與Mockjs來繼續(xù)構(gòu)建模擬服務(wù)器了,來滿足自己的各種需要