json-server React中的應用

json-server

用於Mock數據

安裝json-server

npm install json-server
或 
yarn add json-server

React中的應用

創建React項目

使用creat-react-app 腳手架創建react項目

Mock準備

在項目中創建與src平級的目錄mock

mock目錄中新建.json文件

舉例:

{
  "getUserInfo": {
    "status": 200,
    "msg": "operation success",
    "data": {
      "idCard": "372922****07037891",
      "customerName": "耿銀",
      "phoneNumber": "18364566530",
      "gender": "先生",
      "cuid": 51020584
    }
  },
  "getMockData": {
    "status": 500,
    "msg": "operation success"
  }
}

package.json中添加Mock命令

在package.json中的 scripts 中添加

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

package.json中的 scripts 標籤

...其它內容...
"scripts": {
  "start": "react-scripts start",
  "build": "react-scripts build",
  "test": "react-scripts test",
  "mock": "json-server mock/db.json --port 3003",
  "eject": "react-scripts eject"
}
...其它內容...

啓動Mock服務器

  • 刷新webstorm的npm工具箱
    • 多出一個mock選項
    • 雙擊mock,會啓動json-server
      在這裏插入圖片描述
      在這裏插入圖片描述

Mock數據查看

啓動json-server服務器後,直接在瀏覽器中輸入地址:

http://localhost:+端口號/接口名稱

例如

http://localhost:3003/getUserInfo

會直接返回json數據

 {
    "status": 200,
    "msg": "operation success",
    "data": {
      "idCard": "372922****07037891",
      "customerName": "耿銀",
      "phoneNumber": "18364566530",
      "gender": "先生",
      "cuid": 51020584
    }
  }

Mock的應用

最開始的使用方法

此時使用axios時請求數據,需要添加端口號等,不能使用相對路徑,因爲,前端項目與模擬接口的服務端口不相同;
所以需要編寫公共方法去判斷是不是開發環境,因爲生產環境時,不需要使用前綴 ‘http://localhost:3003’

/**
 * development 開發環境
 * production 生產環境
 */

const getH5Url = () => {
    window.H5_API = "http://localhost:3003";
    if (process.env.NODE_ENV === 'production') {
        window.H5_API = "";//部署同服務中域名相同爲相對路徑即可
    }
}

getH5Url();

/**
 *交互請求地址
 * @type {string}
 */
const getRequestUrl = (mockUrl, realUrl) => {
    let url = mockUrl;
    if (process.env.NODE_ENV === 'production') {
        url = realUrl;
    }
    return window.H5_API + url;
}
/**
*交互方法
*/
axios({
   method: 'get',
   url: getRequestUrl("/mockurl", '/realUrl'),
})
.then((response) => {
   .......
}).catch((err) => {
   .......
});

改進的方式

package.json中添加代理

注意:這個特性可以在[email protected]以及更高版本中使用。

"proxy":"http://localhost:3003",

開發環境的服務器去代理任何開發環境中未知的請求到自己的Mock api服務器,此時無需getH5Url方法了,
因爲此時mock也可以使用相對路徑了

   /**
    *交互請求地址
    * @type {string}
    */
   const getRequestUrl = (mockUrl, realUrl) => {
       let url = mockUrl;
       if (process.env.NODE_ENV === 'production') {
           url = realUrl;
       }
       return url;
   }
  /**
  *交互方法
  */
  axios({
      method: 'get',
      url: getRequestUrl("/mockurl", '/realUrl'),
  })
  .then((response) => {
      .......
  }).catch((err) => {
      .......
  });
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章