axios 學習筆記


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

axios 是一個基於 Promise 的HTTP庫,可以用在瀏覽器和 node.js 中

 

特性:

• 從瀏覽器發起 XMLHttpRequests 請求

• 從 node.js 發起 http 請求

• 支持 Promise API

• 攔截請求和響應

• 轉換請求和響應數據

• 取消請求

• 自動轉換為 JSON 數據

• 客戶端支持防御 XSRF

 

補充Promise:

Promise 是 es6中新增的異步事件處理方式,基本用法如下:

let myFirstPromise = new Promise((resolve, reject) => {
  // 當異步事件處理成功后自動調用 resolve(...)方法,如果失敗的話則調用 reject(...)
  // 在這個例子中,我們使用setTimeout(...) 定時器來模擬異步事件
  setTimeout(function(){
    resolve("Success!"); // 此時,所有代碼運行完畢
  }, 250);
});

myFirstPromise.then((successMessage) => {
    //successMessage 就是上面的resolve(...)方法中所傳入的參數
  console.log("Yay! " + successMessage);
});


// Yay! Success!

Promise對象是一個構造函數,它接收一個函數作為參數,該函數的兩個參數分別是 resolve(字面意思:解決) 和 reject (字面意思:拒絕),它們是兩個函數,由 js 引擎提供,不用自己部署。

resolve 函數的作用是,將 Promise 對象的狀態從“未完成”變為“成功”,在異步操作成功時調用,並將異步操作的結果,作為參數傳遞出去。

reject 函數的作用是,將 Promise 對象的狀態從“未完成”變為“失敗”,在異步操作失敗時調用,並將異步操作報出的錯誤,作為參數傳遞出去

上例中,myFirstPromise 是 Promise 對象創建的一個實例,Promise 實例生成后,可以用 then 方法分別指定 resolve 狀態 和 reject 狀態的回調函數,reject 函數是可選的,不一定要提供

getJSON('/posts.json').then(function(posts) {
  // ...
}).catch(function(error) {
  // 處理 getJSON 和 前一個回調函數運行時發生的錯誤
  console.log('發生錯誤!', error);
});

上面代碼中,getJSON 方法返回一個 Promise 對象,如果該對象狀態變為 resolved,則會調用 then 方法指定的回調函數;如果異步操作拋出異常,狀態就會變為 rejected,同時調用 catch 方法指定的回調函數,處理這個錯誤。另外,then 方法指定的回調函數,如果在運行中拋出錯誤,也會被 catch 方法捕獲

 

安裝:

// 命令行輸入
npm install axios

//引入 axios
import axios from 'axios'

 

官網提供的示例:

執行 GET 請求

// 為給定 ID 的 user 發起請求
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);
  });

執行 POST 請求

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

執行多個並發請求

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) {
    // 兩個請求都已完成
  }));

現在跟着官網的例子來操作下:

Demo 1:成功的發起一個 GET 請求

<button type="button" class="btn btn-primary" @click="get">get</button>
import axios from 'axios';
    export default{
        methods: {
            get () {
                axios.get('../../../static/data/sidenav.json').then(response=>console.log(response))
                                       .catch(error=>console.log(error))
            }
        }
    }

運行結果:

Demo 2:發起 GET 請求失敗,依照上例,訪問一個不存在的 hello.txt 文件

import axios from 'axios';
    export default{
        methods: {
            get () {
                axios.get('./hello.txt').then(response=>console.log(response))
                                       .catch(error=>console.log('錯誤消息:'+error))
            }
        }
    }

運行結果:

 

axios API

可以通過向 axios 傳遞相關配置來創建請求

axios(config)

// 發送一個 POST 請求
axios({
  method: 'post',
  url: '/user/12345',
  data: {
    firstName: 'Fred',
    lastName: 'Flintstone'
  }
});
// 從遠程圖片獲取 GET 請求
axios({
  method:'get',
  url:'http://bit.ly/2mTM3nY',
  responseType:'stream'
})
  .then(function(response) {
  response.data.pipe(fs.createWriteStream('ada_lovelace.jpg'))
});

axios(url[, config])

// 發送一個 GET 請求(默認方法)
axios('/user/12345');

 

請求方法的別名:

為方便起見,所有被支持的請求方法都提供了別名

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

注意:在使用別名方法時,url、method、data 這些屬性都不必在配置中指定


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM