mpvue微信小程序http请求-fly.js
生活随笔
收集整理的這篇文章主要介紹了
mpvue微信小程序http请求-fly.js
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
mpvue微信小程序http請求-fly.js
fly.js是什么?
一個支持所有JavaScript運行環境的基于Promise的、支持請求轉發、強大的http請求庫。可以讓您在多個端上盡可能大限度的實現代碼復用(官網解釋)
fly.js有什么特點:
定位與目標:
Fly 的定位是成為 Javascript http請求的終極解決方案。也就是說,在任何能夠執行 Javascript 的環境,只要具有訪問網絡的能力,Fly都能運行在其上,提供統一的API。
使用方法:
1.結合npm
npm install flyio2.使用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: 24phone:"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);});總結
以上是生活随笔為你收集整理的mpvue微信小程序http请求-fly.js的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: DNF圣托里尼NPC在哪 DNF圣托里尼
- 下一篇: mescroll上拉加载的实现