fly.js是什么?
一個支持所有JavaScript運行環境的基於Promise的、支持請求轉發、強大的http請求庫。可以讓您在多個端上盡可能大限度的實現代碼復用(官網解釋)
fly.js有什么特點:
- 提供統一的 Promise API。
- 瀏覽器環境下,輕量且非常輕量 。
- 支持多種JavaScript 運行環境
- 支持請求/響應攔截器。
- 自動轉換 JSON 數據。
- 支持切換底層 Http Engine,可輕松適配各種運行環境。
- 瀏覽器端支持全局Ajax攔截 。
- H5頁面內嵌到原生 APP 中時,支持將 http 請求轉發到 Native。支持直接請求圖片
定位與目標:
Fly 的定位是成為 Javascript http請求的終極解決方案。也就是說,在任何能夠執行 Javascript 的環境,只要具有訪問網絡的能力,Fly都能運行在其上,提供統一的API。
使用方法:
1.結合npm
npm install flyio
2.使用CDN(瀏覽器中)
<script src="https://unpkg.com/flyio/dist/fly.min.js"></script>
3.UMD(瀏覽器中
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); });
注意⚠️:紅色標出部分