Fly.js 一個基於Promise的、強大的、支持多種JavaScript運行時的http請求庫. 有了它,您可以使用一份http請求代碼在瀏覽器、微信小程序、Weex、Node、React Native、快應用中都能正常運行。同時可以方便配合主流前端框架 ,最大可能的實現 Write Once Run Everywhere。本文主要介紹一下如何在微信小程序中使用flyio。
簡單用法請直接移步官方文檔查看,https://github.com/wendux/fly
下面主要說一下它的攔截器的使用方法:
/** * Created by zhengyi.fu on 2018/8/31. */ import Fly from 'flyio/dist/npm/wx' const fly = new Fly() const host = "https://rmall.ukelink.net" //添加請求攔截器 fly.interceptors.request.use((request) => { wx.showLoading({ title: "加載中", mask:true }); console.log(request); // request.headers["X-Tag"] = "flyio"; // request.headers['content-type']= 'application/json'; request.headers = { "X-Tag": "flyio", 'content-type': 'application/json' }; let authParams = { //公共參數 "categoryType": "SaleGoodsType@sim", "streamNo": "wxapp153570682909641893", "reqSource": "MALL_H5", "appid": "string", "timestamp": new Date().getTime(), "sign": "string" }; request.body && Object.keys(request.body).forEach((val) => { if(request.body[val] === ""){ delete request.body[val] }; }); request.body = { ...request.body, ...authParams } return request; }); //添加響應攔截器 fly.interceptors.response.use( (response) => { wx.hideLoading(); return response.data;//請求成功之后將返回值返回 }, (err) => { //請求出錯,根據返回狀態碼判斷出錯原因 console.log(err); wx.hideLoading(); if(err){ return "請求失敗"; }; } ); fly.config.baseURL = host; export default fly;
用法:將此文件引入main.js然后直接掛載到vue原型上
import fly from './utils/fly'
Vue.prototype.$fly = fly;
然后在頁面或者組件中直接使用:
this.$fly.request({ method:"post", //post/get 請求方式 url:"/mms/country/queryValidZoneListForMallHome", body:{} }).then(res =>{ console.log(res) })
下面在介紹一種微信小程序內置的請求接口的方法:
/** * Created by zhengyi.fu on 2018/8/31. */ const host = 'https://rmall.ukelink.net'; function request(url, method, data, header = {}) { wx.showLoading({ title: '加載中' //數據請求前loading }) return new Promise((resolve, reject) => { wx.request({ url: host + url, //僅為示例,並非真實的接口地址 method: method, data: data, headers: { 'content-type': 'application/json' // 默認值 }, success: function (res) { wx.hideLoading(); resolve(res.data) }, fail: function (error) { wx.hideLoading(); reject(false) }, complete: function () { wx.hideLoading(); } }) }) } function get(obj) { return request(obj.url, 'GET', obj.data) } function post(obj) { return request(obj.url, 'POST', obj.data) } export default { request, get, post, host }
用法:將此文件引入main.js然后直接掛載到vue原型上
import request from './utils/request'
Vue.prototype.$http = request;
然后在頁面或者組件中直接使用:
this.$http.post({ url:"/mms/country/queryValidZoneListForMallHome", data:{ "categoryType":"SaleGoodsType@sim", "streamNo":"web_bss153570682909641893", "reqSource":"MALL_H5", "appid":"string", "timestamp":1535706829096, "sign":"string" } }).then(res =>{ console.log(res) })