Axios 非同步請求用法解析

shohan發表於2019-06-21

官方中文文件


什麼是Axios

  • Axios 是一個基於 Promise 的http庫,使用非常方便
  • 那麼它有哪些特性呢:
    1. 從瀏覽器中建立 XMLHttpRequests
    2. 從 node.js 建立 http 請求
    3. 支援 Promise API
    4. 攔截請求和響應
    5. 轉換請求資料和響應資料
    6. 取消請求
    7. 自動轉換 JSON 資料
    8. 客戶端支援防禦 XSRF

安裝引用

  • npm install axios
  • import axios from 'axios'
使用 cdn <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

下面來講解具體用法:

  • 假設測試的伺服器請求統一在test.php ,內容如下:
<?php
if($_GET){
  echo json_encode(['method'=>'get', 'params'=>$_GET]);
} else if($_POST){
  echo json_encode(['method'=>'post', 'params'=>$_POST]);
} else {
  echo 'unknow method';
}

1. 執行 GET 請求

axios.get('http://localhost/test.php?id=123')
  .then(response => console.log(response.data)) //請求的返回結果存放在response.data
    .catch(error => console.log(error))
或者如果拼接的引數比較多時可以這樣傳參
axios.get('http://localhost/test.php', {
            params: {
                id: 123,
                content: 'some text'
            }
    })
  .then(response => console.log(response.data))
    .catch(error => console.log(error))

2. POST 請求

  • 在使用axios.post()時要注意傳送的資料格式問題
  • 預設情況下,axios將javascrip物件序列化為JSON,
  • 而伺服器端接收的post資料格式為'application/x-www-form-urlencoded'
  • 在這裡引入 qs 庫 npm install qs const Qs = require('qs')
 或使用 cdn <script src="https://cdn.bootcss.com/qs/6.5.1/qs.min.js"></script>
axios.post('http://localhost/test.php', Qs.stringify({
            firstParam: 'first',
            secondParam: 'second',
    }))
    .then(response => console.log(response.data))
    .catch(error => console.log(error))
  • 如果不對資料格式做轉換則不能正常被伺服器接收
  • 如果前端硬是不改變,後端有沒有什麼辦法呢,當然是有的
  • 這裡傳引數據不做處理
   axios.post('http://localhost/test.php', {
            firstParam: 'first',
            secondParam: 'second',
    }).then(response => console.log(response.data))
    .catch(error => console.log(error))

  • test.php 內容做修改
    //這裡使用file_get_contents("php://input"); 接收原始流資料, 這個方式還要以接收檔案和圖片等資源
    $params = file_get_contents("php://input");
    //注意:這裡要把資料json_decode($data, true); 做處理,接收到的只是個字元物件
    echo json_encode(['method'=>'php-input', 'params'=>json_decode($data, true)]);
    //這樣的方式同樣可以正確獲取到資料

3. 執行多個併發請求

axios.all([
    axios.get('http://localhost/test.php?id=123'),
    axios.post('http://localhost/test.php', Qs.stringify({one: 'one', two: 'two'}))
]).then(response => console.log(response))
//執行多個併發請求時,返回的結果放在一個陣列中,且每一項資料格式都和單個請求時的返回是一樣的
//如果要依次獲取列印結果,則如下:
    .then(response => {
        for(let i=0; i<response.length; i++){
            console.log(response[i].data)
        }
    })

4. axios 已封裝好通用的例項方法:

//[, args] 中括號中的選項表示可選引數
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]])

5. 通過向 axios 傳遞相關配置來建立請求

axios({
    method: 'post',
    url: '',
    data: {},
    ......
})

下面是所有的配置項說明:

{
   // `url` 是用於請求的伺服器 URL
  url: '/user',
  // `method` 是建立請求時使用的方法
  method: 'get', // default
  // `baseURL` 將自動加在 `url` 前面,除非 `url` 是一個絕對 URL。
  // 它可以通過設定一個 `baseURL` 便於為 axios 例項的方法傳遞相對 URL
  baseURL: 'https://some-domain.com/api/',
  // `transformRequest` 允許在向伺服器傳送前,修改請求資料
  // 只能用在 'PUT', 'POST' 和 'PATCH' 這幾個請求方法
  // 後面陣列中的函式必須返回一個字串,或 ArrayBuffer,或 Stream
  transformRequest: [function (data, headers) {
    // 對 data 進行任意轉換處理
    return data;
  }],
  // `transformResponse` 在傳遞給 then/catch 前,允許修改響應資料
  transformResponse: [function (data) {
    // 對 data 進行任意轉換處理
    return data;
  }],
  // `headers` 是即將被髮送的自定義請求頭
  headers: {'X-Requested-With': 'XMLHttpRequest'},
  // `params` 是即將與請求一起傳送的 URL 引數
  // 必須是一個無格式物件(plain object)或 URLSearchParams 物件
  params: {
    ID: 12345
  },
   // `paramsSerializer` 是一個負責 `params` 序列化的函式
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function(params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },
  // `data` 是作為請求主體被髮送的資料
  // 只適用於這些請求方法 'PUT', 'POST', 和 'PATCH'
  // 在沒有設定 `transformRequest` 時,必須是以下型別之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 瀏覽器專屬:FormData, File, Blob
  // - Node 專屬: Stream
  data: {
    firstName: 'Fred'
  },
  // `timeout` 指定請求超時的毫秒數(0 表示無超時時間)
  // 如果請求話費了超過 `timeout` 的時間,請求將被中斷
  timeout: 1000,
   // `withCredentials` 表示跨域請求時是否需要使用憑證
  withCredentials: false, // default
  // `adapter` 允許自定義處理請求,以使測試更輕鬆
  // 返回一個 promise 並應用一個有效的響應 (查閱 [response docs](#response-api)).
  adapter: function (config) {
    /* ... */
  },
 // `auth` 表示應該使用 HTTP 基礎驗證,並提供憑據
  // 這將設定一個 `Authorization` 頭,覆寫掉現有的任意使用 `headers` 設定的自定義 `Authorization`頭
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
   // `responseType` 表示伺服器響應的資料型別,可以是 '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` 定義允許的響應內容的最大尺寸
  maxContentLength: 2000,

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

  // `maxRedirects` 定義在 node.js 中 follow 的最大重定向數目
  // 如果設定為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 中用於定義在執行 http 和 https 時使用的自定義代理。允許像這樣配置選項:
  // `keepAlive` 預設沒有啟用
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),

  // 'proxy' 定義代理伺服器的主機名稱和埠
  // `auth` 表示 HTTP 基礎驗證應當用於連線代理,並提供憑據
  // 這將會設定一個 `Proxy-Authorization` 頭,覆寫掉已有的通過使用 `header` 設定的自定義 `Proxy-Authorization` 頭。
  proxy: {
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },

  // `cancelToken` 指定用於取消請求的 cancel token
  // (檢視後面的 Cancellation 這節瞭解更多)
  cancelToken: new CancelToken(function (cancel) {
  })
}

6. 自定義例項預設值

const instance = axios.create({
  baseURL: 'https://api.example.com',
    withCredentials: true, 
  timeout: 5000,
    ......
});

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

新增請求攔截器

const myInterceptor = axios.interceptors.request.use(config => {
    //在傳送請求之前做些什麼
    ......
    return config;
},
error => {
    //對請求錯誤做些什麼
    console.log(error)
    return Promise.reject(error)
})

新增響應攔截器

const myInterceptor = axios.interceptors.response.use(response => {
    //對響應資料做點什麼
    ......
    return response;
},
error => {
    //對錯誤做點什麼
    ......
    return Promise.reject(error)
})

移除攔截器

axios.interceptor.request.eject(myInterceptor)
本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章