Foreword:
Because of the recent need to use uni-app for the development of small programs, I have recently built an environment for small programs. As a front-end Xiaobai who uses vue, he naturally chose uni-app that supports vue. But uni.request that comes with uni needs to be encapsulated by itself (because it is lazy), so I chose flyio for request encapsulation.
Environment configuration:
npm install flyio
here I use npm to install, you can also download the source file
wx,js or wx.umd.min.js
1. First look at how to use npm after installation:
1.1 Create an api.js, initialize a fly instance, and then encapsulate the required interfaces in it.
Here I used easy-mock for interface testing
import Fly from "flyio/dist/npm/wx"
const fly = new Fly;
// 配置请求根域名
fly.config.baseURL = " https://www.easy-mock.com/mock/5df0a676d0843e1ef18f6e7d";
// 配置响应拦截器
fly.interceptors.response.use(
(response) => {
// 如果请求报错
if (response.data.code != 10000) {
uni.showModal({
title: '温馨提示',
content: response.data.data
})
} else {
//只将请求结果的data字段返回
return response.data.data
}
},
(err) => {
//发生网络错误后会走到这里
return Promise.resolve("网络请求:ERROR!")
}
);
// 配置请求拦截器
fly.interceptors.request.use((request) => {
request.headers["token"] = uni.getStorageSync('token');
return request;
});
async function wxLogin() {
return await new Promise((resolve, reject) => {
wx.login({
success(res) {
if (res.code) {
resolve(res.code)
}
}
})
})
}
// 登录
export const login = async (params) => {
console.log('开始登录...');
let code = await wxLogin();
let res = await fly.get('/user/login', {code: code});
uni.setStorageSync('token', res.token);
uni.setStorageSync('openid', res.openid)
};
//普通接口
export const getList = async (params) => {
let res = await fly.get('/getlist', params);
console.log(res)
};
1.2 Then import it globally in main.js or app.vue to use
import Vue from 'vue'
import App from './App'
import * as API from './static/utils/api'
Vue.prototype.$api = API;
Vue.config.productionTip = false;
App.mpType = 'app';
const app = new Vue({
...App
});
app.$mount();
2. First look at how to use npm after installation:
var Fly=require("../lib/wx") //wx.js为您下载的源码文件
var fly=new Fly; //创建fly实例
It's just a different way of introduction.