Nodejs構建mock數據並通過rest api風格調用接口訪問數據
如果我們只有json格式的數據文件,我們想通過訪問url方式調用居然數據
確保電腦安裝node環境
如果你沒有安裝好node環境請移步http://nodejs.cn/
一、安裝json-server
1.新建demo文件
cd demo
2.安裝json-server
npm install -S json-server
3.項目demo目錄下,新建一個 JSON 文件data.json
和一個
package.json文件
db.json
內容如下
{ "posts": [ { "id": 1, "title": "json-server", "author": "typicode" } ], "comments": [ { "id": 1, "body": "some comment", "postId": 1 } ], "profile": { "name": "typicode" } }
package.json內容如下
{ "name": "rest-api-demo", "version": "1.0.0", "description": "", "main": "index.js", "scripts": { "server": "json-server data.json", "test": "..." }, "keywords": [], "author": "", "license": "ISC", "dependencies": { "json-server": "^0.9.4" } }
二、啟動服務
npm run server
三、調用rest 風格api
打開瀏覽器
注意這個的數據獲取只是get方式請求獲取到的,如需POST
、PUT
、DELETE
等 HTTP 方法的數據體進行解析請參考
https://github.com/ruanyf/jstraining/tree/master/demos#rest-api