mpvue微信小程序http請求終極解決方案-fly.js

fly.js是什麼?javascript

  一個支持全部JavaScript運行環境的基於Promise的、支持請求轉發、強大的http請求庫。可讓您在多個端上儘量大限度的實現代碼複用(官網解釋)vue

fly.js有什麼特色:java

  1. 提供統一的 Promise API。
  2. 瀏覽器環境下,輕量且很是輕量 。
  3. 支持多種JavaScript 運行環境
  4. 支持請求/響應攔截器。
  5. 自動轉換 JSON 數據。
  6. 支持切換底層 Http Engine,可輕鬆適配各類運行環境。
  7. 瀏覽器端支持全局Ajax攔截 。
  8. H5頁面內嵌到原生 APP 中時,支持將 http 請求轉發到 Native。支持直接請求圖片

定位與目標:shell

  Fly 的定位是成爲 Javascript http請求的終極解決方案。也就是說,在任何可以執行 Javascript 的環境,只要具備訪問網絡的能力,Fly都能運行在其上,提供統一的API。npm

使用方法: json

1.結合npm小程序

npm install flyio

2.使用CDN(瀏覽器中)微信小程序

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

3.UMD(瀏覽器中api

https://unpkg.com/flyio/dist/umd/fly.umd.min.js

由於做者使用npm在mpvue微信小程序中用到,下面將經驗詳細與你們分享:瀏覽器

npm下載好組建後,我在微信小程序的src/main.js目錄下引用了官網的這段代碼:

var Fly=require("flyio/dist/npm/wx") var fly=new Fly

剛開始在後面加入了這段代碼,

Vue.prototype.$http = fly // 將fly實例掛在vue原型上

可是在post傳參時一直失敗,最後不得不放棄。老老實實在每次使用是用上如下代碼來請求數據:

發起GET請求:

var fly=require("flyio")
//經過用戶id獲取信息,參數直接寫在url中
fly.get('/user?id=133')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

//query參數經過對象傳遞
fly.get('/user', {
      id: 133
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

發起POST請求:

fly.post('/user', {
    name: 'Doris',
    age: 24
    phone:"18513222525"
  })
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

發起多併發請求:

function getUserRecords() {
  return fly.get('/user/133/records');
}

function getUserProjects() {
  return fly.get('/user/133/projects');
}

fly.all([getUserRecords(), getUserProjects()])
  .then(fly.spread(function (records, projects) {
    //兩個請求都完成
  }))
  .catch(function(error){
    console.log(error)
  })

直接用request請求數據:

/直接調用request函數發起post請求
fly.request("/test",{hh:5},{
    method:"post",
    timeout:5000 //超時設置爲5s
 })
.then(d=>{ console.log("request result:",d)})
.catch((e) => console.log("error", e))

以上因爲傳遞參數用上了 { } 花括號,這是傳遞JSON數據參數,不少時候咱們只須要傳遞一個【type=type】就能夠,

因此咱們還能夠用以下方式:

main.js

 

var Fly = require("flyio/dist/npm/wx") 
var fly = new Fly
Vue.prototype.$http = fly // 將fly實例掛在vue原型上

 

index.vue

 


var
newest = String(this.$mp.query.type); this.$http .post( "https://tashimall.miniprogram.weixin-api-test.yokead.com/bulletin/getBulletin.json", "type=" + newest ) .then(res => { //輸出請求數據 this.allBulletin = res.data.data; }) .catch(err => { console.log(err.status, err.message); });

 

注意⚠️:紅色標出部分

相關文章
相關標籤/搜索