老司機帶路:《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的概念vue

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


特色:jquery

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

2.安裝

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

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

初始化項目:  git

 npm init -y

Npm的方式安裝axios github

npm i axios  -D

 

3. Axios簡單示例

1)、get請求ajax

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)、執行多個併發請求vue-router

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函數:vuex

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

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

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

 

代碼:

一、建立axios實例

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

二、發送請求

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

 

總結

以上就是這篇文章的所有內容了,但願本文的內容對你們的學習或者工做能帶來必定的幫助,若是有疑問你們能夠留言交流,謝謝你們來訪個人博客。

相關文章
相關標籤/搜索