首頁  >  文章  >  web前端  >  json-server怎麼做出後端數據

json-server怎麼做出後端數據

php中世界最好的语言
php中世界最好的语言原創
2018-06-08 11:10:391556瀏覽

這次帶給大家json-server怎樣做出後端數據,json-server怎麼會做出後端數據的注意事項有哪些,下面就是實戰案例,一起來看一下。

正開發過程中前後端分離或不分離,介面多半是之後與頁面的開發,所以建立rest的APL的介面給前端提供虛擬的資料是非常必要的所以這裡我使用了json- server作為工具,支援CORS和JSONP跨域請求,支援GET, POST, PUT, PATCH 和DELETE 方法,更提供了一系列的查詢方法,如limit,order等,接下來我把我自己的上使用心寫成文件

安裝

首先必須有node環境(都用到json-server一定會有node環境吧)然後全域安裝json- server

npm install json-server -g

安裝完成後檢查是否全域安裝成功

G:\demo\JavaScript\Vue\Vue one\project\my-project\Vue_two\my-project>json-server -h
index.js [options] <source>
Options:
 --config, -c        Path to config file  [default: "json-server.json"]
 --port, -p         Set port              [default: 3000]
 --host, -H         Set host            [default: "0.0.0.0"]
 --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]
Examples:
 index.js db.json
 index.js file.js
 index.js http://example.com/db.json
https://github.com/typicode/json-server

在專案根目錄建立一個db.json的目錄,然後寫入訊息

{
 "api": [
  {
   "text": "数据统计",
   "link": "#",
   "hot": true
  },
  {
   "text": "数据检测",
   "link": "#",
   "hot": true
  },
  {
   "text": "流量分析",
   "link": "#",
   "hot": true
  },
  {
   "text": "广告发布",
   "link": "#",
   "hot": false
  }
 ]
}

在package.json裡面的scripts裡面加一行指令

  "json": "json-server db.json --port 3003"

在專案目錄執行指令

npm run json

在bash裡面會看到這樣的介面

> vue@1.0.0 json g:\demo\JavaScript\Vue\Vue one\project\my-project\Vue_two\my-project
> json-server db.json --port 3003
 \{^_^}/ hi!
 Loading db.json
 Done
 Resources
 http://localhost:3003/api
 Home
 http://localhost:3003
 Type s + enter at any time to create a snapshot of the database

恭喜啟動成功!

這時候進入網頁進行訪問

這時候就可以進行訪問了

http://localhost:3003/api

可以看到之前寫的json字串

到此json-server啟動完畢

調用的程式碼是這樣的

this.$http.get('http://localhost:3003/api')
   .then((data) => {
    console.log(data.body)
   }, () => {
    console.log('这里是用了vue-source,后端没有接口')
   })

相信看了本文案例你已經掌握了方法,更多精彩請關注php中文網其它相關文章!

推薦閱讀:

如何使用Angular資料綁定機制

怎麼操作日曆範圍選擇外掛

以上是json-server怎麼做出後端數據的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn