axios 學習筆記

來源:互聯網
上載者:User

標籤:錯誤   error   oss   產生   stream   api   就會   ret   方法   

官方文檔地址: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//引入 axiosimport 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 這些屬性都不必在配置中指定

axios 學習筆記

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.