Axios-指南

前言

前端程序與服務(wù)器通信的最常見方式是通過HTTP協(xié)議盆佣。在我們沒有接觸 React拦盹、Angular狈网、Vue 這類 MVVM 的前端框架之前宅广, Jquery 除了優(yōu)秀的前端 DOM 元素操作性以外瀑构,它的$.ajax()函數(shù)還能夠非常便捷的發(fā)起 http 請求●烧耄現(xiàn)在我們已經(jīng)開始使用 MVVM框架進行前端開發(fā),拋棄了對頁面 DOM 元素的操作,難道為了方便的發(fā)起 http 請求世吨,還需要在項目中加載 jquery 或者是手動創(chuàng)建 http 請求嗎澡刹?答案當(dāng)然是不用的,隨著 Vue 作者尤雨溪宣布不再維護 vue-resource耘婚,轉(zhuǎn)而推薦大家使用 axios罢浇,目前在 Vue 社區(qū)中 axios 開始占據(jù) http 庫的主導(dǎo)地位,所以這一章我們就介紹下如何使用 axios 發(fā)起 http 請求边篮。

一己莺、axios

Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中

二戈轿、特點

  • 支持從瀏覽器中創(chuàng)建 XMLHttpRequests
  • 支持從 node.js 創(chuàng)建 http 請求
  • 支持 Promise API
  • 能攔截請求和響應(yīng)
  • 能轉(zhuǎn)換請求數(shù)據(jù)和響應(yīng)數(shù)據(jù)
  • 能取消請求
  • 自動轉(zhuǎn)換 JSON 數(shù)據(jù)
  • 客戶端支持防御 XSRF

三凌受、安裝

    // 使用 npm 安裝
    npm install axios

    // 使用 bower安裝
    bower install axios

    // 使用 cdn 引入
    < script src = "https://unpkg.com/axios/dist/axios.min.js" ></script>

四、例子

【1】發(fā)送一個 get請求

// 通過給定的ID來發(fā)送請求
axios.get('/user?ID=12345')
  .then(function (response) {
    // 成功返回操作
    console.log(response); 
  })
  .catch(function (error) {
    // 失敗返回操作
    console.log(error);
  });

// 以上請求也可以通過這種方式來發(fā)送
axios.get('/user',{
  params:{
    ID:12345
  }
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

【2】發(fā)送一個POST請求

axios.post('/user',{
  firstName: 'Fred',
  lastName: 'Flintstone'
})
.then(function (response) {
  console.log(response);
})
.catch(function (error) {
  console.log(error);
});

【3】同時發(fā)起多個請求

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) {
    // 當(dāng)這兩個請求都完成的時候會觸發(fā)這個函數(shù)思杯,兩個參數(shù)分別代表返回的結(jié)果
  }));

五胜蛉、axios的API

axios可以通過配置(config)來發(fā)送請求

【1】axios(config)

// 發(fā)送一個 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'))
});

【2】axios(url[, config])

// 發(fā)起一個GET請求(GET是默認(rèn)的請求方法)
axios('/user/12345');

六、請求方法別名

為了方便色乾,為所有支持的請求方法均提供了別名誊册。當(dāng)使用別名方法時,url暖璧,method和data等屬性不用在config重復(fù)聲明

axios.request(url);
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]]);

七案怯、并發(fā)(Concurrency)

以下兩個用來處理同時發(fā)生多個請求的輔助函數(shù)

// iterable是一個可以迭代的參數(shù),如數(shù)組等
axios.all(iterable)

// callback要等到所有請求都完成才會執(zhí)行
axios.spread(callback)

八澎办、創(chuàng)建實例

可以使用自定義配置新建一個 axios 實例 axios.create([config])

let instance = axios.cerate({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header':'foobar'}
});

九嘲碱、實例方法

以下是所有可用的實例方法,額外聲明的配置將與利用create創(chuàng)建的實例配置合并

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]])

十局蚀、請求的配置(request config)

這些是創(chuàng)建請求時可以用的配置選項麦锯。只有 url 是必需的。如果沒有指定 method琅绅,請求將默認(rèn)使用 get 方法扶欣。

   {
      // url 是用于請求的服務(wù)器 URL
      url: '/user',

      // method 是創(chuàng)建請求時使用的方法
      method: 'get', // default

      // baseURL 將自動加在 url 前面,除非 url 是一個絕對 URL千扶。
      // 它可以通過設(shè)置一個 baseURL 便于為 axios 實例的方法傳遞相對 URL
      baseURL: 'https://some-domain.com/api/',

      // transformRequest 允許在向服務(wù)器發(fā)送前料祠,修改請求數(shù)據(jù)
      // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
      // 后面數(shù)組中的函數(shù)必須返回一個字符串,或 ArrayBuffer县貌,或 Stream
      transformRequest: [function (data, headers) {
        // 對 data 進行任意轉(zhuǎn)換處理
        return data;
      }],

      // transformResponse 在傳遞給 then/catch 前术陶,允許修改響應(yīng)數(shù)據(jù)
      transformResponse: [function (data) {
        // 對 data 進行任意轉(zhuǎn)換處理
        return data;
      }],

      // headers 是即將被發(fā)送的自定義請求頭
      headers: { 'X-Requested-With': 'XMLHttpRequest' },

      // params 是即將與請求一起發(fā)送的 URL 參數(shù)
      // 必須是一個無格式對象(plain object)或 URLSearchParams 對象
      params: {
        ID: 12345
      },

      // paramsSerializer 是一個負(fù)責(zé) params 序列化的函數(shù)
      // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
      paramsSerializer: function (params) {
        return Qs.stringify(params, { arrayFormat: 'brackets' })
      },

      // data 是作為請求主體被發(fā)送的數(shù)據(jù)
      // 只適用于這些請求方法 'PUT', 'POST', 和 'PATCH'
      // 在沒有設(shè)置 transformRequest 時,必須是以下類型之一:
      // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
      // - 瀏覽器專屬:FormData, File, Blob
      // - Node 專屬: Stream
      data: {
        firstName: 'Fred'
      },

      // timeout 指定請求超時的毫秒數(shù)(0 表示無超時時間)
      // 如果請求話費了超過 timeout 的時間煤痕,請求將被中斷
      timeout: 1000,

      // withCredentials 表示跨域請求時是否需要使用憑證
      withCredentials: false, // default

      // adapter 允許自定義處理請求梧宫,以使測試更輕松
      // 返回一個 promise 并應(yīng)用一個有效的響應(yīng) (查閱 [response docs](#response-api)).
      adapter: function (config) {
        /* ... */
      },

      // auth 表示應(yīng)該使用 HTTP 基礎(chǔ)驗證接谨,并提供憑據(jù)
      // 這將設(shè)置一個 Authorization 頭,覆寫掉現(xiàn)有的任意使用 headers 設(shè)置的自定義 Authorization頭
      auth: {
        username: 'janedoe',
        password: 's00pers3cret'
      },

      // responseType 表示服務(wù)器響應(yīng)的數(shù)據(jù)類型塘匣,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
      responseType: 'json', // default

      // responseEncoding indicates encoding to use for decoding responses
      // Note: Ignored for responseType of 'stream' or client-side requests
      responseEncoding: 'utf8', // default

      // xsrfCookieName 是用作 xsrf token 的值的cookie的名稱
      xsrfCookieName: 'XSRF-TOKEN', // default

      // xsrfHeaderName is the name of the http header that carries the xsrf token value
      xsrfHeaderName: 'X-XSRF-TOKEN', // default

      // onUploadProgress 允許為上傳處理進度事件
      onUploadProgress: function (progressEvent) {
        // Do whatever you want with the native progress event
      },

      // onDownloadProgress 允許為下載處理進度事件
      onDownloadProgress: function (progressEvent) {
        // 對原生進度事件的處理
      },

      // maxContentLength 定義允許的響應(yīng)內(nèi)容的最大尺寸
      maxContentLength: 2000,

      // validateStatus 定義對于給定的HTTP 響應(yīng)狀態(tài)碼是 resolve 或 reject  promise 脓豪。如果 validateStatus 返回 true (或者設(shè)置為 null 或 undefined),promise 將被 resolve; 否則忌卤,promise 將被 rejecte
      validateStatus: function (status) {
        return status >= 200 && status < 300; // default
      },

      // maxRedirects 定義在 node.js 中 follow 的最大重定向數(shù)目
      // 如果設(shè)置為0扫夜,將不會 follow 任何重定向
      maxRedirects: 5, // default

      // socketPath defines a UNIX Socket to be used in node.js.
      // e.g. '/var/run/docker.sock' to send requests to the docker daemon.
      // Only either socketPath or proxy can be specified.
      // If both are specified, socketPath is used.
      socketPath: null, // default

      // httpAgent 和 httpsAgent 分別在 node.js 中用于定義在執(zhí)行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
      // keepAlive 默認(rèn)沒有啟用
      httpAgent: new http.Agent({ keepAlive: true }),
      httpsAgent: new https.Agent({ keepAlive: true }),

      // 'proxy' 定義代理服務(wù)器的主機名稱和端口
      // auth 表示 HTTP 基礎(chǔ)驗證應(yīng)當(dāng)用于連接代理驰徊,并提供憑據(jù)
      // 這將會設(shè)置一個 Proxy-Authorization 頭笤闯,覆寫掉已有的通過使用 header 設(shè)置的自定義 Proxy-Authorization 頭。
      proxy: {
        host: '127.0.0.1',
        port: 9000,
        auth: {
          username: 'mikeymike',
          password: 'rapunz3l'
        }
      },

      // cancelToken 指定用于取消請求的 cancel token
      // (查看后面的 Cancellation 這節(jié)了解更多)
      cancelToken: new CancelToken(function (cancel) {
      })
    }

十一棍厂、響應(yīng)組成(請求返回的內(nèi)容)

response由以下幾部分信息組成

   {
      // data 由服務(wù)器提供的響應(yīng)
      data: {},

      // status 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)碼
      status: 200,

      // statusText 來自服務(wù)器響應(yīng)的 HTTP 狀態(tài)信息
      statusText: 'OK',

      // headers 服務(wù)器響應(yīng)的頭
      headers: {},

      // config 是為請求提供的配置信息
      config: {},

      // 'request'
      // request is the request that generated this response
      // It is the last ClientRequest instance in node.js (in redirects)
      // and an XMLHttpRequest instance the browser
      request: {}
    }

使用 then 時颗味,你將接收下面這樣的響應(yīng)

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

十二、默認(rèn)配置值

你可以指定將被用在各個請求的配置默認(rèn)值

【1】全局修改axios默認(rèn)配置

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

【2】自定義實例默認(rèn)設(shè)置

// 創(chuàng)建實例時修改配置
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 實例創(chuàng)建之后修改配置
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

【3】配置的優(yōu)先級

配置會以一個優(yōu)先順序進行合并牺弹。這個順序是:在 lib/defaults.js 找到的庫的默認(rèn)值浦马,然后是實例的 defaults 屬性,最后是請求的 config 參數(shù)张漂。后者將優(yōu)先于前者

// 創(chuàng)建一個實例晶默,這時的超時時間為系統(tǒng)默認(rèn)的 0
var instance = axios.create();

// 通過instance.defaults重新設(shè)置超時時間為2.5s,因為優(yōu)先級比系統(tǒng)默認(rèn)高
instance.defaults.timeout = 2500;

// 通過request config重新設(shè)置超時時間為5s航攒,因為優(yōu)先級比instance.defaults和系統(tǒng)默認(rèn)都高
instance.get('/longRequest', {
  timeout: 5000
});

十三磺陡、攔截器

可以在then和catch之前攔截請求和響應(yīng)

// 添加請求攔截器
axios.interceptors.request.use(function (config) {
    // 在發(fā)送請求之前做些什么
    return config;
  }, function (error) {
    // 對請求錯誤做些什么
    return Promise.reject(error);
  });

// 添加響應(yīng)攔截器
axios.interceptors.response.use(function (response) {
    // 對響應(yīng)數(shù)據(jù)做點什么
    return response;
  }, function (error) {
    // 對響應(yīng)錯誤做點什么
    return Promise.reject(error);
  });

移除攔截器

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

為axios實例添加一個攔截器

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

十四、錯誤處理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // 發(fā)送請求后漠畜,服務(wù)端返回的響應(yīng)碼不是 2xx   
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // 發(fā)送請求但是沒有響應(yīng)返回
      console.log(error.request);
    } else {
      // 其他錯誤
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

可以用 validateStatus 定義一個http狀態(tài)碼返回的范圍

axios.get('/user/12345', {
  validateStatus: function (status) {
    return status < 500; 
  }
})

十五仅政、取消請求

可以通過cancel token來取消一個請求

可以通過CancelToken.source工廠函數(shù)來創(chuàng)建一個cancel token

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('/user/12345', {
  cancelToken: source.token
}).catch(function(thrown) {
  if (axios.isCancel(thrown)) {
    console.log('Request canceled', thrown.message);
  } else {
     // 處理錯誤
  }
});

axios.post('/user/12345', {
  name: 'new name'
}, {
  cancelToken: source.token
})

// 取消請求(message 參數(shù)是可選的)
source.cancel('Operation canceled by the user.');

還可以通過傳遞一個 executor 函數(shù)到 CancelToken 的構(gòu)造函數(shù)來創(chuàng)建 cancel token

const CancelToken = axios.CancelToken;
let cancel;

axios.get('/user/12345', {
  cancelToken: new CancelToken(function executor(c) {
    // executor 函數(shù)接收一個 cancel 函數(shù)作為參數(shù)
    cancel = c;
  })
});

// cancel the request
cancel();

十六、vue中Axios的封裝

原文:https://juejin.cn/post/6844903652881072141

十七盆驹、參考

axios中文文檔: http://www.axios-js.com/zh-cn/docs/

文章每周持續(xù)更新,可以微信搜索「 前端大集錦 」第一時間閱讀滩愁,回復(fù)【視頻】【書籍】領(lǐng)取200G視頻資料和30本PDF書籍資料

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末躯喇,一起剝皮案震驚了整個濱河市,隨后出現(xiàn)的幾起案子硝枉,更是在濱河造成了極大的恐慌廉丽,老刑警劉巖,帶你破解...
    沈念sama閱讀 221,430評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件妻味,死亡現(xiàn)場離奇詭異正压,居然都是意外死亡,警方通過查閱死者的電腦和手機责球,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,406評論 3 398
  • 文/潘曉璐 我一進店門焦履,熙熙樓的掌柜王于貴愁眉苦臉地迎上來拓劝,“玉大人,你說我怎么就攤上這事嘉裤≈A伲” “怎么了?”我有些...
    開封第一講書人閱讀 167,834評論 0 360
  • 文/不壞的土叔 我叫張陵屑宠,是天一觀的道長厢洞。 經(jīng)常有香客問我,道長典奉,這世上最難降的妖魔是什么躺翻? 我笑而不...
    開封第一講書人閱讀 59,543評論 1 296
  • 正文 為了忘掉前任,我火速辦了婚禮卫玖,結(jié)果婚禮上公你,老公的妹妹穿的比我還像新娘。我一直安慰自己骇笔,他們只是感情好省店,可當(dāng)我...
    茶點故事閱讀 68,547評論 6 397
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著笨触,像睡著了一般懦傍。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上芦劣,一...
    開封第一講書人閱讀 52,196評論 1 308
  • 那天粗俱,我揣著相機與錄音,去河邊找鬼虚吟。 笑死寸认,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的串慰。 我是一名探鬼主播偏塞,決...
    沈念sama閱讀 40,776評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼邦鲫!你這毒婦竟也來了灸叼?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,671評論 0 276
  • 序言:老撾萬榮一對情侶失蹤庆捺,失蹤者是張志新(化名)和其女友劉穎古今,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體滔以,經(jīng)...
    沈念sama閱讀 46,221評論 1 320
  • 正文 獨居荒郊野嶺守林人離奇死亡捉腥,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,303評論 3 340
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了你画。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片抵碟。...
    茶點故事閱讀 40,444評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡桃漾,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出立磁,到底是詐尸還是另有隱情呈队,我是刑警寧澤,帶...
    沈念sama閱讀 36,134評論 5 350
  • 正文 年R本政府宣布唱歧,位于F島的核電站宪摧,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏颅崩。R本人自食惡果不足惜几于,卻給世界環(huán)境...
    茶點故事閱讀 41,810評論 3 333
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望沿后。 院中可真熱鬧沿彭,春花似錦、人聲如沸尖滚。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,285評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽漆弄。三九已至睦裳,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間撼唾,已是汗流浹背廉邑。 一陣腳步聲響...
    開封第一講書人閱讀 33,399評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留倒谷,地道東北人蛛蒙。 一個月前我還...
    沈念sama閱讀 48,837評論 3 376
  • 正文 我出身青樓,卻偏偏與公主長得像渤愁,于是被迫代替她去往敵國和親牵祟。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,455評論 2 359

推薦閱讀更多精彩內(nèi)容