mpvue微信小程序http请求-fly.js
mpvue微信小程序http請(qǐng)求-fly.js
fly.js是什么?
一個(gè)支持所有JavaScript運(yùn)行環(huán)境的基于Promise的、支持請(qǐng)求轉(zhuǎn)發(fā)、強(qiáng)大的http請(qǐng)求庫(kù)。可以讓您在多個(gè)端上盡可能大限度的實(shí)現(xiàn)代碼復(fù)用(官網(wǎng)解釋)
fly.js有什么特點(diǎn):
定位與目標(biāo):
Fly 的定位是成為 Javascript http請(qǐng)求的終極解決方案。也就是說(shuō),在任何能夠執(zhí)行 Javascript 的環(huán)境,只要具有訪問(wèn)網(wǎng)絡(luò)的能力,Fly都能運(yùn)行在其上,提供統(tǒng)一的API。
使用方法:
1.結(jié)合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因?yàn)樽髡呤褂胣pm在mpvue微信小程序中用到,下面將經(jīng)驗(yàn)詳細(xì)與大家分享:
npm下載好組建后,我在微信小程序的src/main.js目錄下引用了官網(wǎng)的這段代碼:
var Fly=require("flyio/dist/npm/wx") var fly=new Fly剛開(kāi)始在后面加入了這段代碼,
Vue.prototype.$http = fly // 將fly實(shí)例掛在vue原型上但是在post傳參時(shí)一直失敗,最后不得不放棄。老老實(shí)實(shí)在每次使用是用上以下代碼來(lái)請(qǐng)求數(shù)據(jù):
發(fā)起GET請(qǐng)求:
?
var fly=require("flyio") //通過(guò)用戶id獲取信息,參數(shù)直接寫在url中 fly.get('/user?id=133').then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});//query參數(shù)通過(guò)對(duì)象傳遞 fly.get('/user', {id: 133}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});發(fā)起POST請(qǐng)求:
fly.post('/user', {name: 'Doris',age: 24phone:"18513222525"}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});發(fā)起多并發(fā)請(qǐng)求:
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) {//兩個(gè)請(qǐng)求都完成})).catch(function(error){console.log(error)})直接用request請(qǐng)求數(shù)據(jù):
/直接調(diào)用request函數(shù)發(fā)起post請(qǐng)求 fly.request("/test",{hh:5},{method:"post",timeout:5000 //超時(shí)設(shè)置為5s}) .then(d=>{ console.log("request result:",d)}) .catch((e) => console.log("error", e))以上由于傳遞參數(shù)用上了 { } 花括號(hào),這是傳遞JSON數(shù)據(jù)參數(shù),很多時(shí)候我們只需要傳遞一個(gè)【type=type】就可以,
所以我們還可以用如下方式:
main.js
?
var Fly = require("flyio/dist/npm/wx") var fly = new Fly Vue.prototype.$http = fly // 將fly實(shí)例掛在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 => {//輸出請(qǐng)求數(shù)據(jù)this.allBulletin = res.data.data;}).catch(err => {console.log(err.status, err.message);});總結(jié)
以上是生活随笔為你收集整理的mpvue微信小程序http请求-fly.js的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: DNF圣托里尼NPC在哪 DNF圣托里尼
- 下一篇: mescroll上拉加载的实现