Axios-指南

前言

前端程序與服務(wù)器通信的最常見方式是通過HTTP協(xié)議。在我們沒有接觸 React、Angular、Vue 這類 MVVM 的前端框架之前, Jquery 除了優(yōu)秀的前端 DOM 元素操作性以外,它的$.ajax()函數(shù)還能夠非常便捷的發(fā)起 http 請求。現(xiàn)在我們已經(jīng)開始使用 MVVM框架進(jìn)行前端開發(fā),拋棄了對頁面 DOM 元素的操作,難道為了方便的發(fā)起 http 請求,還需要在項目中加載 jquery 或者是手動創(chuàng)建 http 請求嗎?答案當(dāng)然是不用的,隨著 Vue 作者尤雨溪宣布不再維護(hù) 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'
  }
});
// 獲取遠(yuǎn)程圖片
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 進(jìn)行任意轉(zhuǎn)換處理
        return data;
      }],

      // transformResponse 在傳遞給 then/catch 前,允許修改響應(yīng)數(shù)據(jù)
      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 表示無超時時間)
      // 如果請求話費了超過 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 允許為上傳處理進(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 時使用的自定義代理。允許像這樣配置選項:
      // keepAlive 默認(rèn)沒有啟用
      httpAgent: new http.Agent({ keepAlive: true }),
      httpsAgent: new https.Agent({ keepAlive: true }),

      // 'proxy' 定義代理服務(wù)器的主機(jī)名稱和端口
      // 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)先順序進(jìn)行合并。這個順序是:在 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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

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

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