天天看點

Vue-cli(四) 項目中引入Axios安裝Axios引入Axios使用

Axios 是一個基于 promise 的 HTTP 庫,可以用在浏覽器和 node.js 中。

  • 從浏覽器中建立 XMLHttpRequest
  • 從 node.js 發出 http 請求
  • 支援 Promise API
  • 攔截請求和響應
  • 轉換請求和響應資料
  • 取消請求
  • 自動轉換JSON資料
  • 用戶端支援防止  CSRF/XSRF

安裝Axios

我們直接使用npm install來進行安裝。

npm install axios --save           

由于axios是需要打包到生産環境中的,是以我們使用--save來進行安裝。 也可以選擇使用cnpm來安裝,加快安裝速度。

引入Axios

隻需要在需要的vue檔案中引入axios就可以。

import axios from 'axios'           

使用

發送一個

GET

請求

//通過給定的ID來發送請求
axios.get('/user?ID=12345')
  .then(function(response){
    console.log(response);
  })
  .catch(function(err){
    console.log(err);
  });
//以上請求也可以通過這種方式來發送
axios.get('/user',{
  params:{
    ID:12345
  }
})
.then(function(response){
  console.log(response);
})
.catch(function(err){
  console.log(err);
});
           

POST

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

一次性并發多個請求

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){
    //當這兩個請求都完成的時候會觸發這個函數,兩個參數分别代表傳回的結果
  }))
           

原文釋出時間為:2018年04月20日

原文作者:

 阿剛ABC

本文來源:

開源中國

如需轉載請聯系原作者

繼續閱讀