老司機帶路:《axios從入門到開車 嘀嘀~~》


前言:axios vue、axios 跨域、axios.js、axios get、axios post、axios中文文檔

  之前當vue更新到2.0之后,作者就宣告不再對vue-resource更新,而是推薦的axios,前一段時間用了一下,現在說一下它的用法。文中介紹的非常詳細,需要的朋友可以參考借鑒,下面來一起看看吧。
——————看到文章最后的小伙伴會有 兩個小禮物

提綱:

  1. Axios的概念
  2. 安裝
  3. Axios簡單示例
  4. Axios的API
  5. Axios的請求配置和響應數據格式
  6. Axios的攔截器
  7. Ajax,jQuery ajax,axios和fetch的區別
  8. vue踩坑之全局使用axios

內容:

1.Axios的概念

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


特點:

  1. 從瀏覽器中創建 XMLHttpRequests
  2. 從 node.js 創建 http 請求
  3. 支持 Promise API
  4. 攔截請求和響應
  5. 轉換請求數據和響應數據
  6. 取消請求
  7. 自動轉換 JSON 數據
  8. 客戶端支持防御 XSRF

2.安裝

安裝nodejs(自帶npm),安裝cnpm(可選)

npm install -g cnpm --registry=https://registry.npm.taobao.org

初始化項目:  

 npm init -y

Npm的方式安裝axios 

npm i axios  -D

 

3. Axios簡單示例

1)、get請求

let vueobj = this;
axios.get('api/goodslists', {
   params: { "goodsid":"01003" }
} )
.then(function (response) {
console.log(response.data);
     vueobj.goodslist = response.data; //把獲取到的數據賦給goodslist
})
.catch(function (error) {
           console.log(error);
});

 

 

2)、執行多個並發請求

getall:function(){
function getbooks(){  return axios.get('api/books');  }
function getreaders(){  return axios.get('api/readers');  }
axios.all([getbooks(), getreaders()]).then(
axios.spread(function (books, readers) { 
//兩個請求都完成后,調用該函數,第一個參數是第一個請求的結果,第二個參數是第二個請求的結果
console.log(books.data);
console.log(readers.data);
})
);
}

 

4.Axios的API

  1. Axios函數
  2. Axios請求的別名
  3. Axios處理並發
  4. 創建一個實例,實例方法

1)、axios函數:

axios(config)。在config對象參數里,除了url外,其它的都可選的屬性。
axios 能夠在進行請求時的一些設置。如:
發起 get請求 let vueobj = this;

axios({ 
method:'get',
url:'api/goodslists', 
 params :{     "goodsid":"01003" }
 })
 .then(function (response) {
 vueobj.goodslist = response.data;
 })
 .catch(function (error) {
     console.log(error);

});

 

 

2)、axios請求的別名:

為了方便,axios提供了所有請求方法的重命名支持,如下:


axios.request(config)
axios.get(url[,config])
axios.delete(url[,config])
axios.head(url[,config])
axios.post(url[,data[,config]])
axios.put(url[,data[,config]])
axios.patch(url[,data[,config]])

     1、axios.request(config)

let vueobj = this;
axios.request({ 
method:'get',
url:'api/goodslists', 
params:{ "goodsid":"01002" }
 })
 .then(function (response) {
 vueobj.goodslist = response.data;
 })
 .catch(function (error) {
     console.log(error);
});

 

2. axios.get(url[,config])

let vueobj = this;
axios.get('api/goodslists', {
params:{
"goodsid":"01003"
 }
})
.then(function (response) {
 vueobj.goodslist = response.data;
})
.catch(function (error) {  
console.log(error);
});

 

3. Axios處理並發( Concurrency)

axios.all(iterable)//all函數執行所有的請求          

axios.spread(callback)//處理響應回來的回調函數

代碼:

getall:function(){
function getbooks(){  return axios.get('api/books');  }
function getreaders(){  return axios.get('api/readers');  }
axios.all([getbooks(), getreaders()]).then(
axios.spread(function (books, readers) { 
//兩個請求都完成后,調用該函數,第一個參數是第一個請求的結果,第二個參數是第二個請求的結果
console.log(books.data);
console.log(readers.data);
})
);
}

 

4.創建一個實例,實例方法

創建一個新的實例
axios.create([config])
實例方法
下面列出了一些實例方法。具體的設置將在實例設置中被合並。
axios#request(config)
axios#get(url[,config])
axios#delete(url[,config])
axios#head(url[,config])
axios#post(url[,data[,config]])
axios#put(url[,data[,config]])

axios#patch(url[,data[,config]])

 

代碼:

1、創建axios實例

var instance = axios.create({ 
method:'get',
url:'api/goodslists', 
params:{  "goodsid":"01002" }
 });

2、發送請求

instance.request()
 .then(function (response) {
 console.log(response.data);
 vueobj.goodslist = response.data;
 })
 .catch(function (error) {
     console.log(error);
});

 

5. Axios的 請求配置和響應數據格式

1)、請求的配置

 

//`url`是服務器鏈接,用來請求用
    url:'/user',
    //`method`是發起請求時的請求方法
    method:`get`,
    //`baseURL`如果`url`不是絕對地址,那么將會加在其前面。
    //當axios使用相對地址時這個設置非常方便
    //在其實例中的方法
    baseURL:'http://some-domain.com/api/',
    //`transformRequest`允許請求的數據在傳到服務器之前進行轉化。
    //這個只適用於`PUT`,`GET`,`PATCH`方法。
    //數組中的最后一個函數必須返回一個字符串,一個`ArrayBuffer`,或者`Stream`
    transformRequest:[function(data){
        //依自己的需求對請求數據進行處理
        return data;
    }],
    //`transformResponse`允許返回的數據傳入then/catch之前進行處理
    transformResponse:[function(data){
        //依需要對數據進行處理
        return data;
    }],
    //`headers`是自定義的要被發送的頭信息
    headers:{'X-Requested-with':'XMLHttpRequest'},
    //`params`是請求連接中的請求參數,必須是一個純對象,或者URLSearchParams對象
    params:{         ID:12345    },




//`paramsSerializer`是一個可選的函數,是用來序列化參數
    //例如:(https://ww.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`定義請求的時間,單位是毫秒。
    //如果請求的時間超過這個設定時間,請求將會停止。
    timeout:1000,
    
    //`withCredentials`表明是否跨域請求,
    //應該是用證書
    withCredentials:false //默認值


    //`adapter`適配器,允許自定義處理請求,這會使測試更簡單。
    //返回一個promise,並且提供驗證返回(查看[response docs](#response-api))
    adapter:function(config){
        /*...*/
    },


//`xsrfHeaderName` 是http頭(header)的名字,並且該頭攜帶xsrf的值
    xrsfHeadername:'X-XSRF-TOKEN',//默認值


    //`onUploadProgress`允許處理上傳過程的事件
    onUploadProgress: function(progressEvent){
        //本地過程事件發生時想做的事
    },


    //`onDownloadProgress`允許處理下載過程的事件
    onDownloadProgress: function(progressEvent){
        //下載過程中想做的事
    },


    //`maxContentLength` 定義http返回內容的最大容量
    maxContentLength: 2000,


    //`validateStatus` 定義promise的resolve和reject。
    //http返回狀態碼,如果`validateStatus`返回true(或者設置成null/undefined),promise將會接受;其他的promise將會拒絕。
    validateStatus: function(status){
        return status >= 200 && stauts < 300;//默認
    },
    //`httpAgent` 和 `httpsAgent`當產生一個http或者https請求時分別定義一個自定義的代理,在nodejs中。
    //這個允許設置一些選選個,像是`keepAlive`--這個在默認中是沒有開啟的。
    httpAgent: new http.Agent({keepAlive:treu}),
    httpsAgent: new https.Agent({keepAlive:true}),


    //`proxy`定義服務器的主機名字和端口號。
    //`auth`表明HTTP基本認證應該跟`proxy`相連接,並且提供證書。
    //這個將設置一個'Proxy-Authorization'頭(header),覆蓋原先自定義的。
    proxy:{
        host:127.0.0.1,
        port:9000,
        auth:{
            username:'cdd',
            password:'123456'
        }
    },

    //`cancelTaken` 定義一個取消,能夠用來取消請求
    //(查看 下面的Cancellation 的詳細部分)
    cancelToke: new CancelToken(function(cancel){
    })
}

 

 

2)、響應數據的格式:

{
    //`data`是服務器的提供的回復(相對於請求)
    data{},

    //`status`是服務器返回的http狀態碼
    status:200,

    //`statusText`是服務器返回的http狀態信息
    statusText: 'ok',

    //`headers`是服務器返回中攜帶的headers
    headers:{},
    //`config`是對axios進行的設置,目的是為了請求(request)
    config:{}

}

 

使用 then ,你會接受打下面的信息

axios.get('/user/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 時,或者傳入一個 reject callback 作為 then 的第二個參數,那么返回的錯誤信息將能夠被使用。

6.Axios的攔截器

你可以在請求或者返回被 then 或者 catch 處理之前對它們進行攔截。

1)、請求攔截器

axios.interceptors.request.use(
  function (config) {//config參數是請求的配置
    config.url=‘api/goodslists’;//發送請求前,修改請求的url
    return config
  }, 
   function (error) {
    console.log('請求失敗')
    return Promise.reject(error)
  }
);

 

2)、響應攔截器

axios.interceptors.response.use(
function (response) {//response參數是響應對象
   response.data.unshift({“goodsid”:“商品編號”,“goodsname”:“商品名稱”,“goodsprice”:“商品價格”});//給響應的數據增加一個對象
   return response;
}, function (error) {
console.log('響應出錯')
return Promise.reject(error)

})

 

3)、請求的代碼:

let vueobj = this;
axios.request({ 
method:'get',
url:'api/readers', 
params:{
 "goodsid":"01002"
}
 })
 .then(function (response) {
 console.log(response.data);
 vueobj.goodslist = response.data;
 })
 .catch(function (error) {
     console.log(error);
});

 

7.Ajax,jQuery ajax,axios和fetch的區別

Ajax:
       ajax自然不必說,最早出現的發送后端請求技術,隸屬於原始js中,核心使用XMLHttpRequest對象,多個請求之間如果有先后關系的話,就會出現回調地獄。
Jquery Ajax:
      是jQuery框架中的發送后端請求技術,由於jQuery是基於原始的基礎上做的封裝,所以,jquery Ajax自然也是原始ajax的封裝
Fetch:
     fetch號稱是AJAX的替代品,是在ES6出現的,使用了ES6中的promise對象。Fetch是基於promise設計的。Fetch的代碼結構比起ajax簡單多了,參數有點像jQuery ajax。但是,一定記住fetch不是ajax的進一步封裝,而是原生js。Fetch函數就是原生js,沒有使用XMLHttpRequest對象。與XMLHttpRequest(XHR)類似,fetch()方法允許你發出AJAX請求。區別在於Fetch API使用Promise,因此是一種簡潔明了的API,比XMLHttpRequest更加簡單易用。

 

fetch("../students.json").then(function(response){
        if(response.status!==200){
            console.log("存在一個問題,狀態碼為:"+response.status);
            return;
        }
        //檢查響應文本
        response.json().then(function(data){
            console.log(data);
        });
}).catch(function(err){
    console.log("Fetch錯誤:"+err);
})

 

mode屬性用來決定是否允許跨域請求,以及哪些response屬性可讀。可選的mode屬性值為 same-origin,no-cors(默認)以及 cores;

  • same-origin模式很簡單,如果一個請求是跨域的,那么返回一個簡單的error,這樣確保所有的請求遵守同源策略
  • no-cors模式允許來自CDN的腳本、其他域的圖片和其他一些跨域資源,但是首先有個前提條件,就是請求的method只能是"HEAD","GET"或者"POST"
  • cors模式我們通常用作跨域請求來從第三方提供的API獲取數據

Response 也有一個type屬性,它的值可能是"basic","cors","default","error"或者"opaque";

  • "basic": 正常的,同域的請求,包含所有的headers除了"Set-Cookie"和"Set-Cookie2"。
  • "cors": Response從一個合法的跨域請求獲得, 一部分header和body 可讀。(限定只能在響應頭中看見“Cache-Control”、“Content-Language”、“Content-Type”、“Expires”、“Last-Modified”以及“Progma”)
  • "error": 網絡錯誤。Response的status是0,Headers是空的並且不可寫。(當Response是從Response.error()中得到時,就是這種類型)
  • "opaque": Response從"no-cors"請求了跨域資源。依靠Server端來做限制。(將不能查看數據,也不能查看響應狀態,也就是說我們不能檢查請求成功與否;目前為止不能在頁面腳本中請求其他域中的資源)

 

復制代碼
function status(response){
    if(response.status>=200 && response.status<300){
        return Promise.resolve(response);
    }else{
        return Promise.reject(new Error(response.statusText));
    }
}
function json(response){
    return response.json();
}
fetch("../students.json",{mode:"cors"})//響應類型“cors”,一般為“basic”;
.then(status)//可以鏈接方法
.then(json)
.then(function(data){
  console.log("請求成功,JSON解析后的響應數據為:",data); })
.then(function(response){
  console.log(response.headers.get('Content-Type')); //application/json
  console.log(response.headers.get('Date')); //Wed, 08 Mar 2017 06:41:44 GMT
  console.log(response.status); //200
  console.log(response.statusText); //ok
  console.log(response.type); //cors
  console.log(response.url); //http://.../students.json })
.catch(function(err){
  console.log("Fetch錯誤:"+err);
})
復制代碼

使用POST方法提交頁面中的一些數據:將method屬性值設置為post,並且在body屬性值中設置需要提交的數據;

credentials屬性決定了cookies是否能跨域得到 : "omit"(默認),"same-origin"以及"include";

復制代碼
var url='...';
fetch(url,{
    method:"post",//or 'GET'
    credentials: "same-origin",//or "include","same-origin":只在請求同域中資源時成功,其他請求將被拒絕。
  headers:{
    "Content-type":"application:/x-www-form-urlencoded:charset=UTF-8"
  },
  body:"name=lulingniu&age=40"
})
.then(status)
.then(json) //JSON進行解析來簡化代碼
.then(function(data){
    console.log("請求成功,JSON解析后的響應數據為:",data);
})
.catch(function(err){
    console.log("Fetch錯誤:"+err);
});
復制代碼

瀏覽器支持:

目前Chrome 42+, Opera 29+, 和Firefox 39+都支持Fetch。微軟也考慮在未來的版本中支持Fetch。

諷刺的是,當IE瀏覽器終於微響應實現了progress事件的時候,XMLHttpRequest也走到了盡頭。 目前,如果你需要支持IE的話,你需要使用一個polyfill庫。

promises介紹: 

這種寫法被稱為composing promises, 是 promises 的強大能力之一。每一個函數只會在前一個 promise 被調用並且完成回調后調用,並且這個函數會被前一個 promise 的輸出調用;

 

 

axios:

  axios不是原生JS的,需要進行安裝,它不帶可以在客戶端使用,也可以在nodejs端使用。Axios也可以在請求和響應階段進行攔截。同樣也是基於promise對象的。具體參照axios的概念

 

 

8.vue踩坑之全局使用axios

Vue 原本有一個官方推薦的 ajax 插件 vue-resource,但是自從 Vue 更新到 2.0 之后,尤雨溪宣布停止更新vue-resource,並推薦大家使用axios之后,越來越多的 Vue 項目,都選擇 axios 來完成 ajax 請求,而大型項目會使用 Vuex 來管理數據

之前一直使用的是 vue-resource插件,在主入口文件引入import VueResource from 'vue-resource'之后,直接使用Vue.use(VueResource)之后即可將該插件全局引用了;

初用axios時,無腦的按照上面的步驟進行全局引用,結果當時是慘慘的。 
看了看文檔,Axios 是一個基於 promise 的 HTTP 庫

axios並沒有install 方法,所以是不能使用vue.use()方法的。 
那么難道每個文件都要來引用一次?解決方法有很多種: 
1.結合 vue-axios使用 
2. axios 改寫為 Vue 的原型屬性 
3.結合 Vuex的action

結合 vue-axios使用

看了vue-axios的源碼,它是按照vue插件的方式去寫的。那么結合vue-axios,就可以去使用vue.use方法了

首先在主入口文件main.js中引用

import axios from 'axios'
import VueAxios from 'vue-axios'

Vue.use(VueAxios,axios);

之后就可以使用了,在組件文件中的methods里去使用了

getNewsList(){
      this.axios.get('api/getNewsList').then((response)=>{
        this.newsList=response.data.data;
      }).catch((response)=>{
        console.log(response);
      })


    },

 

axios 改寫為 Vue 的原型屬性

首先在主入口文件main.js中引用,之后掛在vue的原型鏈上

import axios from 'axios'
Vue.prototype.$ajax= axios

 

在組件中使用

this.$ajax.get('api/getNewsList').then((response)=>{
        this.newsList=response.data.data;
      }).catch((response)=>{
        console.log(response);
      })

 

結合 Vuex的action 
在vuex的倉庫文件store.js中引用,使用action添加方法

import Vue from 'Vue'
import Vuex from 'vuex'

import axios from 'axios'

Vue.use(Vuex)
const store = new Vuex.Store({
  // 定義狀態
  state: {
    user: {
      name: 'xiaoming'
    }
  },
  actions: {
    // 封裝一個 ajax 方法
    login (context) {
      axios({
        method: 'post',
        url: '/user',
        data: context.state.user
      })
    }
  }
})

export default store

 

在組件中發送請求的時候,需要使用 this.$store.dispatch

methods: {
  submitForm () {
    this.$store.dispatch('login')
  }
}

 

 PS:兩個小禮物分享給大家

 

使用vue2.0+mintUI+axios+vue-router:https://github.com/Stevenzwzhai/vue-mobile-application

使用vue2.0+elementUI+axios+vue-router:https://github.com/Stevenzwzhai/vue2.0-elementUI-axios-vueRouter

 

總結

以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作能帶來一定的幫助,如果有疑問大家可以留言交流,謝謝大家來訪我的博客。


免責聲明!

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



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