1. 程式人生 > >axios處理http請求,對比ajax

axios處理http請求,對比ajax

在處理http請求方面,已經不推薦使用vue-resource了,而是使用最新的axios,下面做一個簡單的介紹。

安裝

使用node

npm install axios 

使用cdn

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

基本使用方法

get請求

// Make a request for a user with a given ID
axios.get('/user?ID=12345')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

// Optionally the request above could also be done as
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) {
    // Both requests are now complete
  }));

這個的使用方法其實和原生的ajax是一樣的,一看就懂。

使用 application/x-www-urlencoded 形式的post請求:

var qs = require('qs');
  axios.post('/bbg/goods/get_goods_list_wechat', qs.stringify({"data": JSON.stringify({
    "isSingle": 1,
    "sbid": 13729792,
    "catalog3": 45908012,
    "offset": 0,
    "pageSize": 25
  })}), {
    headers: {
      "content-type": "application/json;charset=UTF-8",
      "Accept": "application/json"
    }
  })
  .then(function (response) {
    // if (response.data.code == 626) {
      console.log(response);
    // }
  }).catch(function (error) {
    console.log(error);
  });

具體使用參考文件: https://github.com/mzabriskie/axios#using-applicationx-www-form-urlencoded-format

注意: 對於post請求,一般情況下,第一個引數是url,第二個引數是要傳送的請求體的資料,第三個引數是對請求的配置。

另外:axios預設是application/json格式的,如果不適用 qs.stringify 這種形式, 即使添加了請求頭 最後的content-type的形式還是 json 的。 

對於post請求,我們也可以使用下面的jquery的ajax來實現:

$.ajax({
          url:'api/bbg/goods/get_goods_list_wechat',
          data:{
            'data': JSON.stringify({
                       "isSingle": 1,
                       "sbid": 13729792,
                       "catalog3": 45908012,
                       "offset": 0,
                       "pageSize": 25
                    })        
          },   
          beforeSend: function(request) {
            request.setRequestHeader("BBG-Key", "ab9ef204-3253-49d4-b229-3cc2383480a6");
          }, 
          type:'post',  
          dataType:'json',  
          success:function(data){      
            console.log(data);
          },
          error: function (error) {
            console.log(err);
          },
          complete: function () {

          }
        });

顯然,通過比較,可以發現,jquery的請求形式更簡單一些,且jqury預設的資料格式就是 application/x-www-urlencoded ,從這方面來講會更加方便一些。

另外,對於兩個同樣的請求,即使都請求成功了,但是兩者請求得到的結果也是不一樣的,如下:

不難看到: 使用axios返回的結果會比jquery的ajax返回的結構(實際的結果)多包裝了一層,包括相關的config、 headers、request等。

對於get請求, 我個人還是推薦使用axios.get()的形式,如下所示:

axios.get('/bbg/shop/get_classify', {
    params: {
      sid:  13729792
    },
    headers: {
      "BBG-Key": "ab9ef204-3253-49d4-b229-3cc2383480a6"
    }
  })
  .then(function (response) {
    if (response.data.code == 130) {
      items = response.data.data;
      store.commit('update', items);
      console.log(items);
    }
    console.log(response.data.code);
  }).catch(function (error) {
    console.log(error);
    console.log(this);
  });

即第一個引數是:url, 第二個引數就是一個配置物件,我們可以在配置物件中設定 params 來傳遞引數。 

個人理解為什麼get沒有第二個引數作為傳遞的查詢字串,而post有第二個引數作為post的資料。

  因為get可以沒有查詢字串,也可以get請求,但是post必須要有post的資料,要不然就沒有使用post的必要了。