使用json-server模擬後臺數據

首先在電腦中需要安裝nodejs,然後全局安裝json server.

npm install json-server -g

使用linux和macos的電腦需要加上sudo

sudo npm install json-server -g

安裝完成後可以用json-server -h命令檢查是否安裝成功,成功後會出現

json-server [options] <source>

選項:
  --config, -c               Path to config file    [默認值: "json-server.json"]
  --port, -p                 Set port                             [默認值: 3000]
  --host, -H                 Set host                        [默認值: "0.0.0.0"]
  --watch, -w                Watch file(s)                                [布爾]
  --routes, -r               Path to routes file
  --middlewares, -m          Paths to middleware files                    [數組]
  --static, -s               Set static files directory
  --read-only, --ro          Allow only GET requests                      [布爾]
  --no-cors, --nc            Disable Cross-Origin Resource Sharing        [布爾]
  --no-gzip, --ng            Disable GZIP Content-Encoding                [布爾]
  --snapshots, -S            Set snapshots directory               [默認值: "."]
  --delay, -d                Add delay to responses (ms)
  --id, -i                   Set database id property (e.g. _id)  [默認值: "id"]
  --foreignKeySuffix, --fks  Set foreign key suffix (e.g. _id as in post_id)
                                                                  [默認值: "Id"]
  --quiet, -q                Suppress log messages from output            [布爾]
  --help, -h                 顯示幫助信息                                 [布爾]
  --version, -v              顯示版本號                                   [布爾]

示例:
  json-server db.json
  json-server file.js
  json-server http://example.com/db.json

https://github.com/typicode/json-server
安裝完成後,在自己的項目目錄下建立一個xxx.json文件,例如mock-data.json,並寫入數據

{
    "users": [
        {
            "id" : 1,
            "username": "aaa",
            "password": "aaa"
        },
        {
            "id" : 2,
            "username": "bbb",
            "password": "bbb"
        },
        {
            "id": 3,
            "username": "ccc",
            "password": "ccc"
        }
    ]   
}

然後使用命令行工具進入該json文件所在目錄,執行json-server --watch xxx.json 【json-server --watch xxx.json --port 3000(端口可隨意指定)

執行成功返回:

\{^_^}/ hi!

  Loading mock-data.json
  Done

  Resources
  http://localhost:3000/users

  Home
  http://localhost:3000



頁面信息:


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章