nodejs構建mock數據


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方式請求獲取到的,如需POSTPUTDELETE等 HTTP 方法的數據體進行解析請參考

https://github.com/ruanyf/jstraining/tree/master/demos#rest-api

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM