Axios

Axios 是一個基于 Promise 的 HTTP 庫,可用于瀏覽器和 node.js

1. 獲取實(shí)例

axios.create([config])

// 發(fā)送 POST 請求
const instance = axios.create({
  baseURL: 'https://some-domain.com/api/',
  timeout: 1000,
  headers: {'X-Custom-Header': 'foobar'}
});

實(shí)例方法

以下是可用的實(shí)例方法。指定的配置將與實(shí)例的配置合并。

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

2. request config(可配置的請求選項(xiàng))

{
  // 請求路徑
  url: 'aa/bb',
  
  // 請求方法
  method: 'get',

  // baseUrl, 如果 url 不是絕對路徑,則會拼接在 url 前面。
  baseUrl: 'http://aa/bb/cc'
  
  // transformRequest ,在請求發(fā)送前對數(shù)據(jù)進(jìn)行轉(zhuǎn)換
  // 僅支持 POST,PUT,PATCH 方法。
  // 數(shù)組中的函數(shù)必須返回 字符串,ArrayBuffer 或者 Stream 其中之一
  transformRequrst: [
    function(data) {
      // 對 data 進(jìn)行轉(zhuǎn)換
      return data
    }
  ],
  // transformResponse, 在返回?cái)?shù)據(jù)傳遞給 then/catch 之前對數(shù)據(jù)進(jìn)行處理
  transformResponse: [
     function(data) {  
      // 對 data 進(jìn)行轉(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 表示無超時時間)
  // 如果請求話費(fèi)了超過 `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ǔ)驗(yàn)證,并提供憑據(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` 允許為上傳處理進(jìn)度事件
  onUploadProgress: function (progressEvent) {
    // Do whatever you want with the native progress event
  },

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

   // `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 時使用的自定義代理。允許像這樣配置選項(xiàng):
  // `keepAlive` 默認(rèn)沒有啟用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' 定義代理服務(wù)器的主機(jī)名稱和端口
  // `auth` 表示 HTTP 基礎(chǔ)驗(yàn)證應(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) {
  })
}

3. response Struct (返回?cái)?shù)據(jù)結(jié)構(gòu))

{
  // `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: {}
}

4. 攔截器

在請求或者響應(yīng)被 thencatch 處理前攔截它們

// 添加請求攔截器
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ù)做點(diǎn)什么
    return response;
  }, function (error) {
    // 對響應(yīng)錯誤做點(diǎn)什么
    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 () {/*...*/});

5. 錯誤處理

axios.get('/user/12345')
  .catch(function (error) {
    if (error.response) {
      // The request was made and the server responded with a status code
      // that falls out of the range of 2xx
      console.log(error.response.data);
      console.log(error.response.status);
      console.log(error.response.headers);
    } else if (error.request) {
      // The request was made but no response was received
      // `error.request` is an instance of XMLHttpRequest in the browser and an instance of
      // http.ClientRequest in node.js
      console.log(error.request);
    } else {
      // Something happened in setting up the request that triggered an Error
      console.log('Error', error.message);
    }
    console.log(error.config);
  });

或者是下面這種方式

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

6.取消請求

可以使用 CancelToken.source 工廠方法創(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();

7. 并發(fā)

axios.all(iterable)
axios.spread(callback)
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

  • 一、安裝 1、 利用npm安裝npm install axios --save 2、 利用bower安裝bower...
    kiddings閱讀 1,911評論 0 3
  • axios 基于 Promise 的 HTTP 請求客戶端,可同時在瀏覽器和 node.js 中使用 功能特性 在...
    Yanghc閱讀 3,744評論 0 7
  • 本周在做一個使用vuejs的前端項(xiàng)目,訪問后端服務(wù)使用axios庫,這里對照官方文檔,簡單記錄下,也方便大家參考。...
    JadePeng閱讀 11,287評論 1 59
  • axios插件的使用操作 axios插件的使用操作 axios [圖片上傳失敗...(image-744a97-1...
    魔仙堡杠把子灬閱讀 3,098評論 0 1
  • 如何引導(dǎo)學(xué)生融入集體
    王靜1879閱讀 304評論 0 0

友情鏈接更多精彩內(nèi)容