Nodejs構建mock數據並經過rest api風格調用接口訪問數據node
若是咱們只有json格式的數據文件,咱們想經過訪問url方式調用竟然數據git
確保電腦安裝node環境github
若是你沒有安裝好node環境請移步http://nodejs.cn/npm
1、安裝json-serverjson
1.新建demo文件api
cd demo瀏覽器
2.安裝json-serverpost
npm install -S json-server
3.項目demo目錄下,新建一個 JSON 文件data.json
和一個
package.json文件url
db.json
內容以下
spa
{ "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" } }
2、啓動服務
npm run server
3、調用rest 風格api
打開瀏覽器
注意這個的數據獲取只是get方式請求獲取到的,如需POST
、PUT
、DELETE
等 HTTP 方法的數據體進行解析請參考
https://github.com/ruanyf/jstraining/tree/master/demos#rest-api