1. 程式人生 > >axios簡單瞭解

axios簡單瞭解

簡單介紹

axios是基於客戶端的promise,面向瀏覽器和nodejs

特色

瀏覽器端發起XMLHttpRequests請求

node端發起http請求

支援Promise API

監聽請求和返回

轉化請求和返回

取消請求

自動轉化json資料

客戶端支援抵禦

get請求(兩種)

//方式一
//發起一個user請求,引數為給定的ID
axios.get('/user?ID=1234')
.then(function(respone){
    console.log(response);
})
.catch(function(error){
    console.log(error);
});
 
//方式二 axios.get('/user',{ params:{ ID:12345 } }) .then(function(respone){ console.log(response); }) .catch(function(error){ console.log(error); });

POST請求

//第一個引數firstName:'friend' 
//第二個引數lastName:'Flintstone'
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([getUserAccount(), getUserPermissions()])
  .then(axios.spread(
function (acct, perms) { // Both requests are now complete }));

請求的配置

{
  //`url`是請求的伺服器地址
  url:'/user',
  //`method`是請求資源的方式
  method:'get'//default
  //如果`url`不是絕對地址,那麼`baseURL`將會加到`url`的前面
  //當`url`是相對地址的時候,設定`baseURL`會非常的方便
  baseURL:'https://some-domain.com/api/',
  //`transformRequest`選項允許我們在請求傳送到伺服器之前對請求的資料做出一些改動
  //該選項只適用於以下請求方式:`put/post/patch`
  //數組裡面的最後一個函式必須返回一個字串、-一個`ArrayBuffer`或者`Stream`
  transformRequest:[function(data){
    //在這裡根據自己的需求改變資料
    return data;
  }],
  //`transformResponse`選項允許我們在資料傳送到`then/catch`方法之前對資料進行改動
  transformResponse:[function(data){
    //在這裡根據自己的需求改變資料
    return data;
  }],
  //`headers`選項是需要被髮送的自定義請求頭資訊
  headers: {'X-Requested-With':'XMLHttpRequest'},
  //`params`選項是要隨請求一起傳送的請求引數----一般連結在URL後面
  //他的型別必須是一個純物件或者是URLSearchParams物件
  params: {
    ID:12345
  },
  //`paramsSerializer`是一個可選的函式,起作用是讓引數(params)序列化
  //例如(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`選項時dada必須是以下幾種型別之一
  //string/plain/object/ArrayBuffer/ArrayBufferView/URLSearchParams
  //僅僅瀏覽器:FormData/File/Bold
  //僅node:Stream
  data {
    firstName:"Fred"
  },
  //`timeout`選項定義了請求發出的延遲毫秒數
  //如果請求花費的時間超過延遲的時間,那麼請求會被終止

  timeout:1000,
  //`withCredentails`選項表明了是否是跨域請求
  
  withCredentials:false,//default
  //`adapter`介面卡選項允許自定義處理請求,這會使得測試變得方便
  //返回一個promise,並提供驗證返回
  adapter: function(config){
    /*..........*/
  },
  //`auth`表明HTTP基礎的認證應該被使用,並提供證書
  //這會設定一個authorization頭(header),並覆蓋你在header設定的Authorization頭資訊
  auth: {
    username:"zhangsan",
    password: "s00sdkf"
  },
  //返回資料的格式
  //其可選項是arraybuffer,blob,document,json,text,stream
  responseType:'json',//default
  //
  xsrfCookieName: 'XSRF-TOKEN',//default
  xsrfHeaderName:'X-XSRF-TOKEN',//default
  //`onUploadProgress`上傳進度事件
  onUploadProgress:function(progressEvent){
    //下載進度的事件
onDownloadProgress:function(progressEvent){
}
  },
  //相應內容的最大值
  maxContentLength:2000,
  //`validateStatus`定義了是否根據http相應狀態碼,來resolve或者reject promise
  //如果`validateStatus`返回true(或者設定為`null`或者`undefined`),那麼promise的狀態將會是resolved,否則其狀態就是rejected
  validateStatus:function(status){
    return status >= 200 && status <300;//default
  },
  //`maxRedirects`定義了在nodejs中重定向的最大數量
  maxRedirects: 5,//default
  //`httpAgent/httpsAgent`定義了當傳送http/https請求要用到的自定義代理
  //keeyAlive在選項中沒有被預設啟用
  httpAgent: new http.Agent({keeyAlive:true}),
  httpsAgent: new https.Agent({keeyAlive:true}),
  //proxy定義了主機名字和埠號,
  //`auth`表明http基本認證應該與proxy代理連結,並提供證書
  //這將會設定一個`Proxy-Authorization` header,並且會覆蓋掉已經存在的`Proxy-Authorization`  header
  proxy: {
    host:'127.0.0.1',
    port: 9000,
    auth: {
      username:'skda',
      password:'radsd'
    }
  },
  //`cancelToken`定義了一個用於取消請求的cancel token
  //詳見cancelation部分
  cancelToken: new cancelToken(function(cancel){

  })
}

請求返回的內容

{
  data:{},
  status:200,
  //從伺服器返回的http狀態文字
  statusText:'OK',
  //響應頭資訊
  headers: {},
  //`config`是在請求的時候的一些配置資訊
  config: {}
}

//例項
axios.get('/user/12345')
  .then(function(res){
    console.log(res.data);
    console.log(res.status);
    console.log(res.statusText);
    console.log(res.headers);
    console.log(res.config);
  })