umi-request:
網絡請求庫,基於fetch封裝,兼具fetch 和 axios 的所有特點,具有緩存,超時,字符編碼處理,錯誤處理等常用功能。
1 支持url 參數自動序列化。
2 post 數據提交方式簡化。
3 api超時支持。
4 api請求緩存支持。
5 支持處理gbk.(gbk 一種字符集)。
6 類axios的request和response攔截器(interceptors)支持。
7 統一的錯誤處理方式。
8 類koa洋蔥機制的use中間件機制支持。
9 類axios的取消處理。(cancel Token).
10 支持Node環境發送http請求。
相較於fetch和axios 而言具有更多的功能,支持取消請求,中間件,超時 ,緩存等功能。
上手的基本示例:
首先,執行get 請求:
1 import request from 'umi-request'; 2 3 request 4 .get('/api/v1/xxx?id=1') 5 .then(function(response) { 6 console.log(response); 7 }) 8 .catch(function(error) { 9 console.log(error); 10 });
同時,也可將請求的url參數放在options,params中:
1 request.get('/api/v1/xxx', { 2 params: { 3 id: 1, 4 }, 5 }) 6 .then(function(response) { 7 console.log(response); 8 }) 9 .catch(function(error) { 10 console.log(error); 11 });
執行基本的post請求:
1 request 2 .post('/api/v1/user', { 3 data: { 4 name: 'Mike', 5 }, 6 }) 7 .then(function(response) { 8 console.log(response); 9 }) 10 .catch(function(error) { 11 console.log(error); 12 });
umi-request的相關API:
可以通過向 umi-request 傳參來發起請求,在method中指定請求方式。
umi-request(url[, options]):
示例:
1 import request from 'umi-request'; 2 3 request('/api/v1/xxx', { 4 method: 'get', 5 params: { id: 1 }, 6 }) 7 .then(function(response) { 8 console.log(response); 9 }) 10 .catch(function(error) { 11 console.log(error); 12 }); 13 14 request('/api/v1/user', { 15 method: 'post', 16 data: { 17 name: 'Mike', 18 }, 19 }) 20 .then(function(response) { 21 console.log(response); 22 }) 23 .catch(function(error) { 24 console.log(error); 25 });
相關請求方法的別名,之后可以不用單獨在method中配置請求方式。
request.get(url[, options]) request.post(url[, options]) request.delete(url[, options]) request.put(url[, options]) request.patch(url[, options]) request.head(url[, options]) request.options(url[, options])
如果有些配置多個請求當中都有使用到,則可以通過extend創建一個umi-request實例,將公共的配置放置在實例中。則可以實現配置的簡化:extend([options])
示例:
1 import { extend } from 'umi-request'; 2 3 const request = extend({ 4 prefix: '/api/v1', 5 timeout: 1000, 6 headers: { 7 'Content-Type': 'multipart/form-data', 8 }, 9 });
之后這個get請求便可以使用extend中的公共配置。
1 request 2 .get('/user') 3 .then(function(response) { 4 console.log(response); 5 }) 6 .catch(function(error) { 7 console.log(error); 8 });
其他的請求方式同理。例如:post delete put patch head options 等。
請求參數的配置:request options 中的參數詳情:
extend options的參數支持以上的所有參數。
參數含義詳情:
1 { 2 // 'method' 是創建請求時使用的方法 3 method: 'get', // default 4 5 // 'params' 是即將於請求一起發送的 URL 參數,參數會自動 encode 后添加到 URL 中 6 // 類型需為 Object 對象或者 URLSearchParams 對象 7 params: { id: 1 }, 8 9 // 'paramsSerializer' 開發者可通過該函數對 params 做序列化(注意:此時傳入的 params 為合並了 extends 中 params 參數的對象,如果傳入的是 URLSearchParams 對象會轉化為 Object 對象 10 paramsSerializer: function (params) { 11 return Qs.stringify(params, { arrayFormat: 'brackets' }) 12 }, 13 14 // 'data' 作為請求主體被發送的數據 15 // 適用於這些請求方法 'PUT', 'POST', 和 'PATCH' 16 // 必須是以下類型之一: 17 // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams 18 // - 瀏覽器專屬:FormData, File, Blob 19 // - Node 專屬: Stream 20 data: { name: 'Mike' }, 21 22 // 'headers' 請求頭 23 headers: { 'Content-Type': 'multipart/form-data' }, 24 25 // 'timeout' 指定請求超時的毫秒數(0 表示無超時時間) 26 // 如果請求超過了 'timeout' 時間,請求將被中斷並拋出請求異常 27 timeout: 1000, 28 29 // ’prefix‘ 前綴,統一設置 url 前綴 30 // ( e.g. request('/user/save', { prefix: '/api/v1' }) => request('/api/v1/user/save') ) 31 prefix: '', 32 33 // ’suffix‘ 后綴,統一設置 url 后綴 34 // ( e.g. request('/api/v1/user/save', { suffix: '.json'}) => request('/api/v1/user/save.json') ) 35 suffix: '', 36 37 // 'credentials' 發送帶憑據的請求 38 // 為了讓瀏覽器發送包含憑據的請求(即使是跨域源),需要設置 credentials: 'include' 39 // 如果只想在請求URL與調用腳本位於同一起源處時發送憑據,請添加credentials: 'same-origin' 40 // 要改為確保瀏覽器不在請求中包含憑據,請使用credentials: 'omit' 41 credentials: 'same-origin', // default 42 43 // ’useCache‘ 是否使用緩存,當值為 true 時,GET 請求在 ttl 毫秒內將被緩存,緩存策略唯一 key 為 url + params + method 組合 44 useCache: false, // default 45 46 // ’ttl‘ 緩存時長(毫秒), 0 為不過期 47 ttl: 60000, 48 49 // 'maxCache' 最大緩存數, 0 為無限制 50 maxCache: 0, 51 52 // 根據協議規范, GET 請求用於獲取、查詢服務端數據,在數據更新頻率不頻繁的情況下做必要的緩存能減少服務端的壓力,因為緩存策略是默認對 GET 請求做緩存,但對於一些特殊場景需要緩存其他類型請求的響應數據時,我們提供 validateCache 供用戶自定義何時需要進行緩存, key 依舊為 url + params + method 53 validateCache: (url, options) => { return options.method.toLowerCase() === 'get' }, 54 55 // 'requestType' 當 data 為對象或者數組時, umi-request 會根據 requestType 動態添加 headers 和設置 body(可傳入 headers 覆蓋 Accept 和 Content-Type 頭部屬性): 56 // 1. requestType === 'json' 時, (默認為 json ) 57 // options.headers = { 58 // Accept: 'application/json', 59 // 'Content-Type': 'application/json;charset=UTF-8', 60 // ...options.headers, 61 // } 62 // options.body = JSON.stringify(data) 63 // 2. requestType === 'form' 時, 64 // options.headers = { 65 // Accept: 'application/json', 66 // 'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8', 67 // ...options.headers, 68 // }; 69 // options.body = query-string.stringify(data); 70 // 3. 其他 requestType 71 // options.headers = { 72 // Accept: 'application/json', 73 // ...options.headers, 74 // }; 75 // options.body = data; 76 requestType: 'json', // default 77 78 // ’parseResponse‘ 是否對請求返回的 Response 對象做格式、狀態碼解析 79 parseResponse: true, // default 80 81 // ’charset‘ 當服務端返回的數據編碼類型為 gbk 時可使用該參數,umi-request 會按 gbk 編碼做解析,避免得到亂碼, 默認為 utf8 82 // 當 parseResponse 值為 false 時該參數無效 83 charset: 'gbk', 84 85 // 'responseType': 如何解析返回的數據,當 parseResponse 值為 false 時該參數無效 86 // 默認為 'json', 對返回結果進行 Response.text().then( d => JSON.parse(d) ) 解析 87 // 其他(text, blob, arrayBuffer, formData), 做 Response[responseType]() 解析 88 responseType: 'json', // default 89 90 // 'throwErrIfParseFail': 當 responseType 為 json 但 JSON.parse(data) fail 時,是否拋出異常。默認不拋出異常而返回 Response.text() 后的結果,如需要拋出異常,可設置 throwErrIfParseFail 為 true 91 throwErrIfParseFail: false, // default 92 93 // 'getResponse': 是否獲取源 Response, 返回結果將包含一層: { data, response } 94 getResponse: false,// default 95 96 // 'errorHandler' 統一的異常處理,供開發者對請求發生的異常做統一處理,詳細使用請參考下方的錯誤處理文檔 97 errorHandler: function(error) { /* 異常處理 */ }, 98 99 // 'cancelToken' 取消請求的 Token,詳細使用請參考下方取消請求文檔 100 cancelToken: null, 101 }
實例化請求實例之后,若還需要動態更新參數,umi-request中的extendOptions方法供用戶進行更新。
const request = extend({ timeout: 1000, params: { a: '1' } }); // 默認參數是 { timeout: 1000, params: { a: '1' }} request.extendOptions({ timeout: 3000, params: { b: '2' } }); // 此時默認參數是 { timeout: 3000, params: { a: '1', b: '2' }}
響應結構:
響應對象Response如下:
1 { 2 // `data` 由服務器提供的響應, 需要進行解析才能獲取 3 data: {}, 4 5 // `status` 來自服務器響應的 HTTP 狀態碼 6 status: 200, 7 8 // `statusText` 來自服務器響應的 HTTP 狀態信息 9 statusText: 'OK', 10 11 // `headers` 服務器響應的頭 12 headers: {}, 13 }
當 options.getResponse === false 時, 響應結構為解析后的 data:
request.get('/api/v1/xxx', { getResponse: false }).then(function(data) { console.log(data); });
當 options.getResponse === true 時,響應結構為包含 data 和 Response 的對象:
request.get('/api/v1/xxx', { getResponse: true }).then(function({ data, response }) { console.log(data); console.log(response.status); console.log(response.statusText); console.log(response.headers); });
錯誤處理:
1 import request, { extend } from 'umi-request'; 2 3 const errorHandler = function(error) { 4 const codeMap = { 5 '021': '發生錯誤啦', 6 '022': '發生大大大大錯誤啦', 7 // .... 8 }; 9 if (error.response) { 10 // 請求已發送但服務端返回狀態碼非 2xx 的響應 11 console.log(error.response.status); 12 console.log(error.response.headers); 13 console.log(error.data); 14 console.log(error.request); 15 console.log(codeMap[error.data.status]); 16 } else { 17 // 請求初始化時出錯或者沒有響應返回的異常 18 console.log(error.message); 19 } 20 21 throw error; // 如果throw. 錯誤將繼續拋出. 22 23 // 如果return, 則將值作為返回. 'return;' 相當於return undefined, 在處理結果時判斷response是否有值即可. 24 // return {some: 'data'}; 25 }; 26 27 // 1. 作為統一錯誤處理 28 const extendRequest = extend({ errorHandler }); 29 30 // 2. 單獨特殊處理, 如果配置了統一處理, 但某個api需要特殊處理. 則在請求時, 將errorHandler作為參數傳入. 31 request('/api/v1/xxx', { errorHandler }); 32 33 // 3. 通過 Promise.catch 做錯誤處理 34 request('/api/v1/xxx') 35 .then(function(response) { 36 console.log(response); 37 }) 38 .catch(function(error) { 39 return errorHandler(error); 40 });
中間件機制,詳情請轉至:https://github.com/umijs/umi-request/blob/master/README_zh-CN.md