国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

詳解vue axios中文文檔

2019-11-19 15:29:00
字體:
來源:轉載
供稿:網友

axios中文文檔

在用Vue做開發的時候,官方推薦的前后端通信插件是axios,Github上axios的文檔雖然詳細,但是卻是英文版.現在發現有個axios的中文文檔,于是就轉載過來了!

原文地址 : https://github.com/mzabriskie/axios

簡介

版本:v0.16.1

基于http客戶端的promise,面向瀏覽器和nodejs

特色

  • 瀏覽器端發起XMLHttpRequests請求
  • node端發起http請求
  • 支持Promise API
  • 攔截請求和返回
  • 轉化請求和返回(數據)
  • 取消請求
  • 自動轉化json數據
  • 客戶端支持抵御XSRF(跨站請求偽造)

安裝

使用npm:

$ npm i axios

使用 bower

$ bower instal axios

使用cdn

<!--國內bootCDN--><script src="https://cdn.bootcss.com/axios/0.16.0/axios.min.js"></script>

示例

發起一個GET請求

//發起一個user請求,參數為給定的IDaxios.get('/user?ID=1234').then(function(respone){  console.log(response);}).catch(function(error){  console.log(error);});//上面的請求也可選擇下面的方式來寫axios.get('/user',{  params:{    ID:12345  }})  .then(function(response){    console.log(response);  })  .catch(function(error){    console.log(error)  });

發起一個POST請求

axios.post('/user',{  firstName:'friend',  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([getUerAccount(),getUserPermissions()])  .then(axios.spread(function(acc,pers){    //兩個請求現在都完成  }));

axios API

可以對axios進行一些設置來生成請求。

axios(config)

//發起 POST請求axios({  method:'post',//方法  url:'/user/12345',//地址  data:{//參數    firstName:'Fred',    lastName:'Flintstone'  }});
//通過請求獲取遠程圖片axios({  method:'get',  url:'http://bit.ly/2mTM3Ny',  responseType:'stream'})  .then(function(response){    response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))  })

axios(url[,config])

//發起一個GET請求axios('/user/12345/);

請求方法的重命名。

為了方便,axios提供了所有請求方法的重命名支持

  • axios.request(config)
  • axios.get(url[,config])
  • axios.delete(url[,config])
  • axios.head(url[,config])
  • axios.options(url[,config])
  • axios.post(url[,data[,config]])
  • axios.put(url[,data[,config]])
  • axios.patch(url[,data[,config]])

注意

當時用重命名方法時url,method,以及data屬性不需要在config中指定。

并發 Concurrency

有用的方法

  • axios.all(iterable)
  • axios.spread(callback)

創建一個實例

你可以使用自定義設置創建一個新的實例

axios.create([config])

var instance = axios.create({  baseURL:'http://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]])

Requese Config請求設置

以下列出了一些請求時的設置選項。只有url是必須的,如果沒有指明method的話,默認的請求方法是GET.

{  //`url`是服務器鏈接,用來請求  url:'/user',  //`method`是發起請求時的請求方法  method:`get`,  //`baseURL`如果`url`不是絕對地址,那么將會加在其前面。  //當axios使用相對地址時這個設置非常方便  //在其實例中的方法  baseURL:'http://some-domain.com/api/',  //`transformRequest`允許請求的數據在傳到服務器之前進行轉化。  //這個只適用于`PUT`,`GET`,`PATCH`方法。  //數組中的最后一個函數必須返回一個字符串或者一個`ArrayBuffer`,或者`Stream`,`Buffer`實例,`ArrayBuffer`,`FormData`  transformRequest:[function(data){    //依自己的需求對請求數據進行處理    return data;  }],  //`transformResponse`允許返回的數據傳入then/catch之前進行處理  transformResponse:[function(data){    //依需要對數據進行處理    return data;  }],  //`headers`是自定義的要被發送的頭信息  headers:{'X-Requested-with':'XMLHttpRequest'},  //`params`是請求連接中的請求參數,必須是一個純對象,或者URLSearchParams對象  params:{    ID:12345  },  //`paramsSerializer`是一個可選的函數,是用來序列化參數  //例如:(https://ww.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  //-僅瀏覽器:FormData,File,Blob  //-僅Node:Stream  data:{    firstName:'fred'  },  //`timeout`定義請求的時間,單位是毫秒。  //如果請求的時間超過這個設定時間,請求將會停止。  timeout:1000,  //`withCredentials`表明是否跨網站訪問協議,  //應該使用證書  withCredentials:false //默認值  //`adapter`適配器,允許自定義處理請求,這會使測試更簡單。  //返回一個promise,并且提供驗證返回(查看[response docs](#response-api))  adapter:function(config){    /*...*/  },  //`auth`表明HTTP基礎的認證應該被使用,并且提供證書。  //這個會設置一個`authorization` 頭(header),并且覆蓋你在header設置的Authorization頭信息。  auth:{    username:'janedoe',    password:'s00pers3cret'  },  //`responsetype`表明服務器返回的數據類型,這些類型的設置應該是  //'arraybuffer','blob','document','json','text',stream'  responsetype:'json',  //`xsrfHeaderName` 是http頭(header)的名字,并且該頭攜帶xsrf的值  xrsfHeadername:'X-XSRF-TOKEN',//默認值  //`onUploadProgress`允許處理上傳過程的事件  onUploadProgress: function(progressEvent){    //本地過程事件發生時想做的事  },  //`onDownloadProgress`允許處理下載過程的事件  onDownloadProgress: function(progressEvent){    //下載過程中想做的事  },  //`maxContentLength` 定義http返回內容的最大容量  maxContentLength: 2000,  //`validateStatus` 定義promise的resolve和reject。  //http返回狀態碼,如果`validateStatus`返回true(或者設置成null/undefined),promise將會接受;其他的promise將會拒絕。  validateStatus: function(status){    return status >= 200 && stauts < 300;//默認  },  //`httpAgent` 和 `httpsAgent`當產生一個http或者https請求時分別定義一個自定義的代理,在nodejs中。  //這個允許設置一些選選個,像是`keepAlive`--這個在默認中是沒有開啟的。  httpAgent: new http.Agent({keepAlive:treu}),  httpsAgent: new https.Agent({keepAlive:true}),  //`proxy`定義服務器的主機名字和端口號。  //`auth`表明HTTP基本認證應該跟`proxy`相連接,并且提供證書。  //這個將設置一個'Proxy-Authorization'頭(header),覆蓋原先自定義的。  proxy:{    host:127.0.0.1,    port:9000,    auth:{      username:'cdd',      password:'123456'    }  },  //`cancelTaken` 定義一個取消,能夠用來取消請求  //(查看 下面的Cancellation 的詳細部分)  cancelToken: new CancelToken(function(cancel){  })}

返回響應概要 Response Schema

一個請求的返回包含以下信息

{  //`data`是服務器的提供的回復(相對于請求)  data{},  //`status`是服務器返回的http狀態碼  status:200,  //`statusText`是服務器返回的http狀態信息  statusText: 'ok',  //`headers`是服務器返回中攜帶的headers  headers:{},  //`config`是對axios進行的設置,目的是為了請求(request)  config:{}}

使用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);  });

使用catch時,或者傳入一個reject callback作為then的第二個參數,那么返回的錯誤信息將能夠被使用。

默認設置(Config Default)

你可以設置一個默認的設置,這設置將在所有的請求中有效。

全局默認設置 Global axios defaults

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';

實例中自定義默認值 Custom instance default

//當創建一個實例時進行默認設置var instance = axios.create({  baseURL:'https://api.example.com'});//在實例創建之后改變默認值instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

設置優先級 Config order of precedence

設置(config)將按照優先順序整合起來。首先的是在lib/defaults.js中定義的默認設置,其次是defaults實例屬性的設置,最后是請求中config參數的設置。越往后面的等級越高,會覆蓋前面的設置。

看下面這個例子:

//使用默認庫的設置創建一個實例,//這個實例中,使用的是默認庫的timeout設置,默認值是0。var instance = axios.create();//覆蓋默認庫中timeout的默認值//此時,所有的請求的timeout時間是2.5秒instance.defaults.timeout = 2500;//覆蓋該次請求中timeout的值,這個值設置的時間更長一些instance.get('/longRequest',{  timeout:5000});

攔截器 interceptors

你可以在請求或者返回被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);});

如果你需要在稍后移除攔截器,你可以

var myInterceptor = axios.interceptors.request.use(function(){/*...*/});axios.interceptors.rquest.eject(myInterceptor);

你可以在一個axios實例中使用攔截器

var instance = axios.create();instance.interceptors.request.use(function(){/*...*/});

錯誤處理 Handling Errors

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時視為錯誤  }});

取消 Cancellation

你可以使用cancel token取消一個請求

axios的cancel token API是基于**cnacelable promises proposal**,其目前處于第一階段。

你可以使用CancelToken.source工廠函數創建一個cancel token,如下:

var CancelToken = axios.CancelToken;var source = CancelToken.source();axios.get('/user/12345', {  cancelToken:source.toke}).catch(function(thrown){  if(axiso.isCancel(thrown)){    console.log('Rquest canceled', thrown.message);  }else{    //handle error  }});//取消請求(信息參數設可設置的)source.cancel("操作被用戶取消");

你可以給CancelToken構造函數傳遞一個executor function來創建一個cancel token:

var CancelToken = axios.CancelToken;var cancel;axios.get('/user/12345', {  cancelToken: new CancelToken(function executor(c){    //這個executor 函數接受一個cancel function作為參數    cancel = c;  })});//取消請求cancel();

注意:你可以使用同一個cancel token取消多個請求。

使用 application/x-www-form-urlencoded 格式化

默認情況下,axios串聯js對象為JSON格式。為了發送application/x-wwww-form-urlencoded格式數據,
你可以使用一下的設置。

瀏覽器 Browser

在瀏覽器中你可以如下使用URLSearchParams API:

var params = new URLSearchParams();params.append('param1','value1');params.append('param2','value2');axios.post('/foo',params);

注意:URLSearchParams不支持所有的瀏覽器,但是這里有個墊片(poly fill)可用(確保墊片在瀏覽器全局環境中)

其他方法:你可以使用qs庫來格式化數據。

var qs = require('qs');axios.post('/foo', qs.stringify({'bar':123}));

Node.js

在nodejs中,你可以如下使用querystring:

var querystring = require('querystring');axios.post('http://something.com/', querystring.stringify({foo:'bar'}));

你同樣可以使用qs庫。

promises

axios 基于原生的ES6 Promise 實現。如果環境不支持請使用墊片.

TypeScript

axios 包含TypeScript定義

import axios from 'axios'axios.get('/user?ID=12345')

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 寻乌县| 西贡区| 井研县| 睢宁县| 霍山县| 安图县| 澄江县| 新晃| 绍兴市| 和顺县| 龙里县| 彝良县| 冷水江市| 彰化市| 进贤县| 峨山| 桦川县| 大厂| 福鼎市| 綦江县| 镇巴县| 盈江县| 罗源县| 罗定市| 从江县| 雷州市| 湖北省| 富锦市| 和政县| 铜梁县| 名山县| 宁化县| 赫章县| 陈巴尔虎旗| 新民市| 江都市| 老河口市| 云林县| 山阳县| 德阳市| 钟祥市|