標籤:rfc package promise 工廠 ram asi page body 相同
轉載:https://www.cnblogs.com/libin-1/p/6607945.html
引入方式:
$ npm install axios$ cnpm install axios //taobao源$ bower install axios或者使用cdn:<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
舉個栗子:執行 GET 請求
// 向具有指定ID的使用者發出請求axios.get(‘/user?ID=12345‘).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);}); // 也可以通過 params 對象傳遞參數axios.get(‘/user‘, {params: {ID: 12345}}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);})執行 POST 請求
axios.post(‘/user‘, {firstName: ‘Fred‘,lastName: ‘Flintstone‘}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});執行多個並發請求
function getUserAccount() {return axios.get(‘/user/12345‘);} function getUserPermissions() {return axios.get(‘/user/12345/permissions‘);} axios.all([getUserAccount(), getUserPermissions()]).then(axios.spread(function (acct, perms) {//兩個請求現已完成}));axios API
可以通過將相關配置傳遞給 axios 來進行請求。
axios(config)
// 發送一個 POST 請求axios({method: ‘post‘,url: ‘/user/12345‘,data: {firstName: ‘Fred‘,lastName: ‘Flintstone‘}});axios(url[, config])
// 發送一個 GET 請求 (GET請求是預設請求模式)axios(‘/user/12345‘);
要求方法別名
為了方便起見,已經為所有支援的要求方法提供了別名。
- axios.request(config)
- axios.get(url [,config])
- axios.delete(url [,config])
- axios.head(url [,config])
- axios.post(url [,data [,config]])
- axios.put(url [,data [,config]])
- axios.patch(url [,data [,config]])
注意
當使用別名方法時,不需要在config中指定url,method和data屬性。
並發
協助函數處理並發請求。
- axios.all(iterable)
- axios.spread(callback)
建立執行個體
您可以使用自訂配置建立axios的新執行個體。
axios.create([config])
var instance = axios.create({baseURL: ‘https://some-domain.com/api/‘,timeout: 1000,headers: {‘X-Custom-Header‘: ‘foobar‘}});
執行個體方法可用的執行個體方法如下所示。 指定的配置將與執行個體配置合并。
axios#request(config)
axios#get(url [,config])
axios#delete(url [,config])
axios#head(url [,config])
axios#post(url [,data [,config]])
axios#put(url [,data [,config]])
axios#patch(url [,data [,config]])
請求配置
這些是用於發出請求的可用配置選項。 只有url是必需的。 如果未指定方法,請求將預設為GET。
{// `url`是將用於請求的伺服器URLurl: ‘/user‘, // `method`是發出請求時使用的要求方法method: ‘get‘, // 預設 // `baseURL`將被添加到`url`前面,除非`url`是絕對的。// 可以方便地為 axios 的執行個體設定`baseURL`,以便將相對 URL 傳遞給該執行個體的方法。baseURL: ‘https://some-domain.com/api/‘, // `transformRequest`允許在請求資料發送到伺服器之前對其變更// 這隻適用於要求方法‘PUT‘,‘POST‘和‘PATCH‘// 數組中的最後一個函數必須返回一個字串,一個 ArrayBuffer或一個 Stream transformRequest: [function (data) {// 做任何你想要的資料轉換 return data;}], // `transformResponse`允許在 then / catch之前對響應資料變更transformResponse: [function (data) {// Do whatever you want to transform the data return data;}], // `headers`是要發送的自訂 headersheaders: {‘X-Requested-With‘: ‘XMLHttpRequest‘}, // `params`是要與請求一起發送的URL參數// 必須是純對象或URLSearchParams對象params: {ID: 12345}, // `paramsSerializer`是一個可選的函數,負責序列化`params`// (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)paramsSerializer: function(params) {return Qs.stringify(params, {arrayFormat: ‘brackets‘})}, // `data`是要作為請求主體發送的資料// 僅適用於要求方法“PUT”,“POST”和“PATCH”// 當沒有設定`transformRequest`時,必須是以下類型之一:// - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams// - Browser only: FormData, File, Blob// - Node only: Streamdata: {firstName: ‘Fred‘}, // `timeout`指定請求逾時之前的毫秒數。// 如果請求的時間超過‘timeout‘,請求將被中止。timeout: 1000, // `withCredentials`指示是否跨網站存取控制請求// should be made using credentialswithCredentials: false, // default // `adapter‘允許自訂處理請求,這使得測試更容易。// 返回一個promise並提供一個有效響應(參見[response docs](#response-api))adapter: function (config) {/* ... */}, // `auth‘表示應該使用 HTTP 基本認證,並提供憑據。// 這將設定一個`Authorization‘頭,覆蓋任何現有的`Authorization‘自訂頭,使用`headers`設定。auth: {username: ‘janedoe‘,password: ‘s00pers3cret‘}, // “responseType”表示伺服器將響應的資料類型// 包括 ‘arraybuffer‘, ‘blob‘, ‘document‘, ‘json‘, ‘text‘, ‘stream‘responseType: ‘json‘, // default //`xsrfCookieName`是要用作 xsrf 令牌的值的cookie的名稱xsrfCookieName: ‘XSRF-TOKEN‘, // default // `xsrfHeaderName`是攜帶xsrf令牌值的http頭的名稱xsrfHeaderName: ‘X-XSRF-TOKEN‘, // default // `onUploadProgress`允許處理上傳的進度事件onUploadProgress: function (progressEvent) {// 使用本地 progress 事件做任何你想要做的}, // `onDownloadProgress`允許處理下載的進度事件onDownloadProgress: function (progressEvent) {// Do whatever you want with the native progress event}, // `maxContentLength`定義允許的http響應內容的最大大小maxContentLength: 2000, // `validateStatus`定義是否解析或拒絕給定的promise// HTTP響應狀態代碼。如果`validateStatus`返回`true`(或被設定為`null` promise將被解析;否則,promise將被 // 拒絕。validateStatus: function (status) {return status >= 200 && status < 300; // default}, // `maxRedirects`定義在node.js中要遵循的重新導向的最大數量。// 如果設定為0,則不會遵循重新導向。maxRedirects: 5, // 預設 // `httpAgent`和`httpsAgent`用於定義在node.js中分別執行http和https請求時使用的自訂代理。// 允許配置類似`keepAlive`的選項,// 預設情況下不啟用。httpAgent: new http.Agent({ keepAlive: true }),httpsAgent: new https.Agent({ keepAlive: true }), // ‘proxy‘定義Proxy 伺服器的主機名稱和連接埠// `auth`表示HTTP Basic auth應該用於串連到代理,並提供credentials。// 這將設定一個`Proxy-Authorization` header,覆蓋任何使用`headers`設定的現有的`Proxy-Authorization` 自訂 headers。proxy: {host: ‘127.0.0.1‘,port: 9000,auth: : {username: ‘mikeymike‘,password: ‘rapunz3l‘}}, // “cancelToken”指定可用於取消請求的取消令牌// (see Cancellation section below for details)cancelToken: new CancelToken(function (cancel) {})}
使用 then 時,您將收到如下響應:
axios.get(‘/user/12345‘).then(function(response) {console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});
配置預設值
您可以指定將應用於每個請求的配置預設值。
全域axios預設值
axios.defaults.baseURL = ‘https://api.example.com‘;axios.defaults.headers.common[‘Authorization‘] = AUTH_TOKEN;axios.defaults.headers.post[‘Content-Type‘] = ‘application/x-www-form-urlencoded‘;
自訂執行個體預設值
//在建立執行個體時設定配置預設值var instance = axios.create({ baseURL:‘https://api.example.com‘}); //在執行個體建立後改變預設值instance.defaults.headers.common [‘Authorization‘] = AUTH_TOKEN;配置優先順序順序
配置將與優先順序合并。 順序是lib / defaults.js中的庫預設值,然後是執行個體的defaults屬性,最後是請求的config參數。 後者將優先於前者。 這裡有一個例子。
//使用庫提供的配置預設值建立執行個體//此時,逾時配置值為`0`,這是庫的預設值var instance = axios.create(); //覆蓋庫的逾時預設值//現在所有請求將在逾時前等待2.5秒instance.defaults.timeout = 2500; //覆蓋此請求的逾時,因為它知道需要很長時間instance.get(‘/ longRequest‘,{ timeout:5000});攔截器
你可以截取請求或響應在被 then 或者 catch 處理之前
//添加請求攔截器axios.interceptors.request.use(function(config){ //在發送請求之前做某事 return config; },function(error){ //請求錯誤時做些事 return Promise.reject(error); }); //添加響應攔截器axios.interceptors.response.use(function(response){ //對響應資料做些事 return response; },function(error){ //請求錯誤時做些事 return Promise.reject(error); });
你可以將攔截器添加到axios的自訂執行個體。
var myInterceptor = axios.interceptors.request.use(function () {/*...*/});axios.interceptors.request.eject(myInterceptor);
如果你以後可能需要刪除攔截器。
var instance = axios.create();instance.interceptors.request.use(function () {/*...*/});處理錯誤
axios.get(‘/ user / 12345‘) .catch(function(error){ if(error.response){ //請求已發出,但伺服器使用狀態碼進行響應 //落在2xx的範圍之外 console.log(error.response.data); console.log(error.response.status); console.log(error.response.headers); } else { //在設定觸發錯誤的請求時發生了錯誤 console.log(‘Error‘,error.message); }} console.log(error.config); });
您可以使用validateStatus配置選項定義自訂HTTP狀態代碼錯誤範圍。
axios.get(‘/ user / 12345‘,{ validateStatus:function(status){ return status < 500; //僅當狀態碼大於或等於500時拒絕 }}})
消除
您可以使用取消令牌取消請求。
axios cancel token API基於可取消的promise提議,目前處於階段1。
您可以使用CancelToken.source工廠建立一個取消令牌,如下所示:
var CancelToken = axios.CancelToken;var source = CancelToken.source(); axios.get(‘/user/12345‘, {cancelToken: source.token}).catch(function(thrown) {if (axios.isCancel(thrown)) {console.log(‘Request canceled‘, thrown.message);} else {// 處理錯誤}}); //取消請求(訊息參數是可選的)source.cancel(‘操作被使用者取消。‘);
您還可以通過將執行器函數傳遞給CancelToken建構函式來建立取消令牌:
var CancelToken = axios.CancelToken;var cancel; axios.get(‘/ user / 12345‘,{ cancelToken:new CancelToken(function executor(c){ //一個執行器函數接收一個取消函數作為參數 cancel = c; })}); // 取消請求clear();
注意:您可以使用相同的取消令牌取消幾個請求。
使用application / x-www-form-urlencoded格式
預設情況下,axios將JavaScript對象序列化為JSON。 要以應用程式/ x-www-form-urlencoded格式發送資料,您可以使用以下選項之一。
瀏覽器
在瀏覽器中,您可以使用URLSearchParams API,如下所示:
var params = new URLSearchParams();params.append(‘param1‘, ‘value1‘);params.append(‘param2‘, ‘value2‘);axios.post(‘/foo‘, params);
或者,您可以使用qs庫對資料進行編碼:請注意,所有瀏覽器都不支援URLSearchParams,但是有一個polyfill可用(確保polyfill全域環境)。
var qs = require(‘qs‘);axios.post(‘/foo‘, qs.stringify({ ‘bar‘: 123 });Node.js在node.js中,可以使用querystring模組,如下所示:
var querystring = require(‘querystring‘);axios.post(‘http://something.com/‘, querystring.stringify({ foo: ‘bar‘ });
你也可以使用qs庫。
Promise
axios 依賴本機要支援ES6 Promise實現。 如果您的環境不支援ES6 Promises,您可以使用polyfill。
TypeScript
axios包括TypeScript定義。
import axios from ‘axios‘;axios.get(‘/user?ID=12345‘);
axios在很大程度上受到Angular提供的$http服務的啟發。 最終,axios努力提供一個在Angular外使用的獨立的$http-like服務。
vue axios全攻略