我們安裝好flyio之后
npm install flyio
找到src目錄下的main.js文件
首先引入flyjs并實(shí)例化
var Fly=require("flyio/dist/npm/wx") var fly=new Fly
比方說我們每次請(qǐng)求我們自己的服務(wù)器接口的時(shí)候需要帶上appID,用戶登陸后需要帶上openId
// 請(qǐng)求攔截 fly.interceptors.request.use((request)=>{ request.body.appId = 'xxx' // 用戶的openId在獲取之后添加到全局變量中如果存在,我們將它添加到請(qǐng)求參數(shù)里面 let openId = Vue.prototype.globalData.openId; if(openId){ request.body.openId = openId } })
當(dāng)服務(wù)器發(fā)生錯(cuò)誤,或者用戶網(wǎng)絡(luò)錯(cuò)誤導(dǎo)致請(qǐng)求失敗的時(shí)候,我們可以添加一個(gè)響應(yīng)攔截
// 響應(yīng)攔截 fly.interceptors.response.use( (response) => { }, (err) => { //發(fā)生網(wǎng)絡(luò)錯(cuò)誤后會(huì)走到這里 //return Promise.resolve("ssss") wx.hideLoading(); wx.showToast({ title:'網(wǎng)絡(luò)不流暢,請(qǐng)稍后再試!', icon:'none', }); })
最后將flyjs掛載到vue的原型上
// 將fly掛載在Vue的原型上 Vue.prototype.$flyio = fly
不同頁面直接使用this.$flyio請(qǐng)求(是不是很方便)
示例:
fly里面的攔截機(jī)制還是很強(qiáng)大的,并且在錯(cuò)誤返回信息做了優(yōu)化處理,在fly攔截器中支持執(zhí)行異步任務(wù),就是說在請(qǐng)求數(shù)據(jù)的時(shí)候如果攔截到token不存在那么我們就可以在攔截器中重新獲取token,再接著執(zhí)行之前的請(qǐng)求。
const Fly = require("flyio/dist/npm/wx") const fly = new Fly Vue.prototype.$http = fly; fly.interceptors.request.use((request) => { //給所有請(qǐng)求添加自定義header if (api.Get('token')) { request.timeout = 30000, request.headers = { "content-type": "application/json", "cld.stats.page_entry": api.Get('scene'), "version": store.state.version, "token": api.Get('token') } wx.showLoading({ title: "加載中", mask: true, }); return request; } else { fly.lock();//鎖住請(qǐng)求 return Public.Load().then(res => { request.timeout = 30000, request.headers = { "content-type": "application/json", "cld.stats.page_entry": api.Get('scene'), "version": store.state.version, "token": api.Get('token') } wx.showLoading({ title: "加載中", mask: true, }); //等待token返回之后在解鎖, fly.unlock(); return request;//繼續(xù)之前的請(qǐng)求, }) } }) fly.interceptors.response.use( (response) => { wx.hideLoading(); return response }, (err) => { wx.hideLoading(); if (err.status == 0) { return "網(wǎng)絡(luò)連接異常" } else if (err.status == 1) { return "網(wǎng)絡(luò)連接超時(shí)" } else if (err.status == 401) { return "用戶未登錄" } else { if (err.response.data.message) { return err.response.data.message } else { return '請(qǐng)求數(shù)據(jù)失敗,請(qǐng)稍后再試' } }; // Do something with response error } )
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識(shí),若有侵權(quán)等問題請(qǐng)及時(shí)與本網(wǎng)聯(lián)系,我們將在第一時(shí)間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com