學習 Antd Pro 前後端分離
- 2019 年 10 月 25 日
- 筆記
1.前言
最近學習reactjs ,前些年用RN開發過移動端,入門還算輕鬆。現在打算使用 Antd Pro 實現前後端分離。要使用Antd Pro這個腳手架,必須熟悉 umi、dva、redux-saga 等相關知識。
基礎知識及目錄結構可以先看官方文檔 : https://pro.ant.design/docs/getting-started-cn
官方介紹:
Ant Design Pro 是一個企業級中後台前端/設計解決方案,我們秉承 [Ant Design](http://ant.design/) 的設計價值觀,致力於在設計規範和基礎組件的基礎上,繼續向上構建,提煉出典型模板/業務組件/配套設計資源,進一步提升企業級中後台產品設計研發過程中的『用戶』和『設計者』的體驗。
2. 網絡請求庫添加鉤子
鉤子的目的主要是對請求頭設置(如:添加 token,api服務端通過token鑒權,當然您的token格式也可以是jwt,我這裡是自己加密後的字符串)和對請求返回的數據實現攔截過濾特殊處理。
antd pro 使用的是 umi-request.js 這個庫,其實也是基於 fetch 封裝 。 一開始用axios替換了request.js裏面。後來發現umi-request 也很容添加鉤子,這裡在umi-request上添加。
添加攔截鉤子:
-
提交請求格式(根據你的api服務選擇):
payload(json格式提交) : ‘Content-Type’: ‘application/json’,
formData (表單格式提交) : ‘Content-Type’: ‘application/x-www-form-urlencoded’
-
token:
系統用戶登錄後存儲在
localStorage -> zone-token
-
返回攔截 :(request.interceptors.response):
我的api返回格式是:
{code:int,msg:string,data:object}
通過返回的code值 提示 token 過期 、token校驗失敗,做相應處理(跳出登錄等等處理)
或其他特殊碼(code)提示及處理
srcutilsrequest.js 調整後代碼
/** * request 網絡請求工具 */ import { extend } from 'umi-request'; import { notification } from 'antd'; import router from 'umi/router'; const codeMessage = { 200: '服務器成功返回請求的數據。', 201: '新建或修改數據成功。', 202: '一個請求已經進入後台排隊(異步任務)。', 204: '刪除數據成功。', 400: '發出的請求有錯誤,服務器沒有進行新建或修改數據的操作。', 401: '用戶沒有權限(令牌、用戶名、密碼錯誤)。', 403: '用戶得到授權,但是訪問是被禁止的。', 404: '發出的請求針對的是不存在的記錄,服務器沒有進行操作。', 406: '請求的格式不可得。', 410: '請求的資源被永久刪除,且不會再得到的。', 422: '當創建一個對象時,發生一個驗證錯誤。', 500: '服務器發生錯誤,請檢查服務器。', 502: '網關錯誤。', 503: '服務不可用,服務器暫時過載或維護。', 504: '網關超時。', }; /** * 異常處理程序 */ const errorHandler = error => { const { response = {} } = error; const errortext = codeMessage[response.status] || response.statusText; const { status, url } = response; if (status === 401) { notification.error({ message: '未登錄或登錄已過期,請重新登錄。', }); // @HACK /* eslint-disable no-underscore-dangle */ window.g_app._store.dispatch({ type: 'login/logout', }); return; } notification.error({ message: `請求錯誤 ${status}: ${url}`, description: errortext, }); // environment should not be used if (status === 403) { router.push('/exception/403'); return; } if (status <= 504 && status >= 500) { router.push('/exception/500'); return; } if (status >= 404 && status < 422) { router.push('/exception/404'); } }; /** * 配置request請求時的默認參數 */ const request = extend({ errorHandler, // 默認錯誤處理 credentials: 'include', // 默認請求是否帶上cookie }); request.interceptors.request.use(async (url, options) => { let token = localStorage.getItem("zone-token"); const headers = { 'Content-Type': 'application/json', //'Content-Type': 'application/x-www-form-urlencoded', 'Accept': 'application/json', }; if (token) { headers['token'] = token; } return ( { url: url, options: { ...options, headers: headers }, } ); }) request.interceptors.response.use((response, options) => { //攔截返回後的特殊處理 // if(response.data.code == 1000001){ // console.log(response.data.msg) // //通過返回的code 提示 token 過期 、token校驗失敗,做相應跳轉 // } return response; }); export default request;
3. 權限及登錄調整
前後台整理中,後在寫。。。。。