Vue 網(wǎng)絡(luò)請求框架 axios 使用教程

前期回顧

1. Vue 學習入門指南
2. Vue 入門環(huán)境搭建
3. Visual Studio Code 使用指南

公眾號:代碼集中營
每周分享技術(shù)文章、優(yōu)質(zhì)軟件資源

axios 是一個基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端,網(wǎng)絡(luò)請求框架。

支持的瀏覽器:

一、安裝axios

  1. 打開vs code ,導(dǎo)入我們之前創(chuàng)建好的vue項目 helloword ,打開終端,敲入下面的安裝命令:
$ npm install axios --save
  1. 安裝完成后,你就好在package.json --》dependencies 里面看到我們加入的網(wǎng)絡(luò)請求庫:axios ,這里簡單介紹一下 dependencies ,類似于android 的Gradle ,添加依賴庫,所以的依賴庫均會在這里


    image.png

二、axios 使用

  1. 找到要加入如網(wǎng)絡(luò)請求的界面,這里以App.vue 作為例子
  2. 加入一個按鈕作為事件點擊
    <button v-on:click="clickTest">獲取 干貨集中營 數(shù)據(jù)</button>
  1. 導(dǎo)入axios
import axios from 'axios'
  1. 編寫事件,由于我們的事件方法名字叫:clickTest,所以我們需要在methods里面新增一個clickTest方法,來處理網(wǎng)絡(luò)請求事件,這里我們拿干貨集中營里面的api來做測試

接口地址:https://gank.io/api/v2/banners

//按鈕點擊測試
    clickTest() {
      axios
        .get("https://gank.io/api/v2/banners")
        .then(function (response) {
          console.log(response.data);
          console.log(response.status);
          console.log(response.statusText);
          console.log(response.headers);
          console.log(response.config);
        })
        .catch(function (error) {
          console.log(error);
        });
    },
image.png
  1. 執(zhí)行終端命令,訪問地址:http://localhost:8080/
    點擊按鈕事件,測試我們的代碼是否正確,效果如圖,我們把網(wǎng)絡(luò)請求數(shù)據(jù)已經(jīng)輸出到控制臺了
npm run serve
image.png

三、API 指南

1. GET 請求

// 直接在 URL 上添加參數(shù) ID=12345
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  })
  .catch(function (error) {
    console.log(error);
  });
 
// 也可以通過 params 設(shè)置參數(shù):
axios.get('/user', {
    params: {
      ID: 12345
    }
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

2. POST 請求

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

3. 執(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í)行完成
  }));

4. 配置攔截器,用于攔截請求

// 添加請求攔截器
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);
  });

5. 請求配置項所有參數(shù)

下面是對應(yīng)的參數(shù),我們需要變更那個,只需要修改對應(yīng)的值即可,沒修改,系統(tǒng)會執(zhí)行默認值

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

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

  // `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) {
    // 對 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` 是一個負責 `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, // 默認的

  // `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", // 默認的

  // `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` 定義允許的響應(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 &gt;= 200 &amp;&amp; status &lt; 300; // 默認的
  },

  // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數(shù)目
  // 如果設(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" 定義代理服務(wù)器的主機名稱和端口
  // `auth` 表示 HTTP 基礎(chǔ)驗證應(yī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) {
  })
}

6. 配置基礎(chǔ)地址(baseURL)

此次只配置了幾個常用的參數(shù),如baseUrl,請求超時限制、Content-Type等,如有用到其他參數(shù),請參考第五條--》請求配置項所有參數(shù)

axios.defaults.baseURL = 'https://api.example.com';
instance.defaults.timeout = 2500;
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

官方文檔:https://github.com/axios/axios

?著作權(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ù)。

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