axios 的入門學習筆記

這段時間接觸了axios 。記錄下學習筆記。

Promise based HTTP client for the browser and node.js

<details>
<summary>特色</summary>

  • 使用來自瀏覽器的'XMLHttpRequests'請求
  • 可以來自node.js的http請求
  • 支持promise
  • 攔截請求和響應
  • 轉換請求和響應數(shù)據(jù)
  • 取消請求
  • 自動轉換來自json的數(shù)據(jù)
  • 客戶端支持防止XSRF(這是一種跨域請求的偽造,是一種對網(wǎng)站的惡意利用)

</details>

支持的瀏覽器

支持的瀏覽器

用法

Using npm:

$ npm install axios

Using bower:

$ bower install axios

Using cdn:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Example

執(zhí)行GET請求

// 為給定 ID 的 user 創(chuàng)建請求
axios.get('/user?ID=12345')
  .then(function (response) {
    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);
  });

執(zhí)行POST請求

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

執(zhí)行多個并發(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) {
    // 兩個請求現(xiàn)在都執(zhí)行完成
  }));

API

  • axios(config)
  • 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]])

處理并發(fā)請求的函數(shù)

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

配置

{
  // `url` 是用于請求的服務器 URL
  url: '/user',

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

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

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

    return data;
  }],

  // `transformResponse` 在傳遞給 then/catch 前,允許修改響應數(shù)據(jù)
  transformResponse: [function (data) {
    // 對 data 進行任意轉換處理

    return data;
  }],

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

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

  // `paramsSerializer` 是一個負責 `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'
  // 在沒有設置 `transformRequest` 時,必須是以下類型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 瀏覽器專屬:FormData, File, Blob
  // - Node 專屬: Stream
  data: {
    firstName: 'Fred'
  },

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

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

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

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

  // `responseType` 表示服務器響應的數(shù)據(jù)類型,可以是 'arraybuffer', 'blob', 'document', 'json', 'text', 'stream'
  responseType: 'json', // 默認的

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

  // `xsrfHeaderName` 是承載 xsrf token 的值的 HTTP 頭的名稱
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默認的

  // `onUploadProgress` 允許為上傳處理進度事件
  onUploadProgress: function (progressEvent) {
    // 對原生進度事件的處理
  },

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

  // `maxContentLength` 定義允許的響應內容的最大尺寸
  maxContentLength: 2000,

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

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

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

  // 'proxy' 定義代理服務器的主機名稱和端口
  // `auth` 表示 HTTP 基礎驗證應當用于連接代理,并提供憑據(jù)
  // 這將會設置一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設置的自定義 `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) {
  })
}

響應結構

{
  // `data` 由服務器提供的響應
  data: {},

  // `status` 來自服務器響應的 HTTP 狀態(tài)碼
  status: 200,

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

  // `headers` 服務器響應的頭
  headers: {},

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

配置默認值/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';

自定義實例默認值

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

配置的優(yōu)先順序

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

// 使用由庫提供的配置的默認值來創(chuàng)建實例
// 此時超時配置的默認值是 `0`
var instance = axios.create();

// 覆寫庫的超時默認值
// 現(xiàn)在,在超時前,所有請求都會等待 2.5 秒
instance.defaults.timeout = 2500;

// 為已知需要花費很長時間的請求覆寫超時設置
instance.get('/longRequest', {
  timeout: 5000
});

攔截器

在請求或響應 被 then 或 catch 處理前攔截它們;

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

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

如果你想在稍后移除攔截器,可以這樣:

var myInterceptor = axios.interceptors.request.use(function () {/*...*/});
axios.interceptors.request.eject(myInterceptor);
?著作權歸作者所有,轉載或內容合作請聯(lián)系作者
【社區(qū)內容提示】社區(qū)部分內容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發(fā)布,文章內容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內容

  • Spring Cloud為開發(fā)人員提供了快速構建分布式系統(tǒng)中一些常見模式的工具(例如配置管理,服務發(fā)現(xiàn),斷路器,智...
    卡卡羅2017閱讀 136,569評論 19 139
  • 時間2017-03-31 13:43:44Hope’s Blog 原文https://blog.ygxdxx.co...
    蕭玄辭閱讀 15,343評論 3 16
  • 在學習了之前的路由vue-router和狀態(tài)管理vuex之后,就應該是網(wǎng)絡交互了。就學習尤大推薦的axios了。剛...
    VioletJack閱讀 40,270評論 18 84
  • 我看見我在尋求"我不行""我不配"的痛苦感受,我全心地接納這種感受,并且放下對它的需要。 發(fā)了朋友圈,過一會想去看...
    Enely娟紅閱讀 227評論 0 0
  • 本周遭遇重創(chuàng),臨近七夕,狗糧吃多了就感覺不舒服,所以情緒有一定的波動,一旦情緒出現(xiàn),就容易傾向于自暴自棄,結果書沒...
    神勇小輝閱讀 267評論 2 0

友情鏈接更多精彩內容