Flyio封装API接口(uniapp开发微信小程序)

Flyio封装API接口

1)flyio 是什么?

2)flyio能干什么?

3)flyio使用


1)flyio 是什么?

一个支持所有JavaScript运行环境的基于Promise的、支持请求转发、强大的http请求库。可以让您在多个端上尽可能大限度的实现代码复用。

2)flyio能干什么?

Fly.js 是一个基于 promise 的,轻量且强大的Javascript http 网络库,它有如下特点:

  1. 提供统一的 Promise API。
  2. 浏览器环境下,轻量且非常轻量 。
  3. 支持多种JavaScript 运行环境
  4. 支持请求/响应拦截器。
  5. 自动转换 JSON 数据。
  6. 支持切换底层 Http Engine,可轻松适配各种运行环境。
  7. 浏览器端支持全局Ajax拦截 。
  8. H5页面内嵌到原生 APP 中时,支持将 http 请求转发到 Native。支持直接请求图片。
3)flyio使用

1、安装(使用npm或yarn等)

npm install flyio

2、微信小程序中引入flyio,新建utils文件夹,在文件夹中新建request.js

let Fly = require("flyio/dist/npm/wx")
let fly = new Fly

3、全局请求配置

//设置超时
fly.config.timeout = 30000;
//设置请求基地址
fly.config.baseURL = 'https://uniapp.dcloud.io/api';

4、拦截器

// 添加请求拦截器
fly.interceptors.request.use((request) => {
    // 给所有请求添加自定义header,带上token信息让服务器验证用户登陆
    let token = uni.getStorageSync('aliToken');
    request.headers['Authorization'] = token;
    // 在当前页面显示导航条加载动画
    uni.showNavigationBarLoading();
    return request;
})
// 添加响应拦截器,响应拦截器会在then/catch处理之前执行
fly.interceptors.response.use(
    (response) => {
        if (response.data.errorNo != 0) {
            uni.showToast({
                title: response.data.errorInfo,
                icon: 'none',
            });
        }
        uni.hideNavigationBarLoading()
        return response.data; //请求成功之后将返回值返回
    },
    (err) => {
        // 在当前页面隐藏导航条加载动画
        uni.hideNavigationBarLoading()

        if (err.status === 0) {
            uni.showToast({
                title: '网络请求延时',
                icon: "none",
            });
            return Promise.reject(err);
        }
        let code = err.response.status;
		if (code === 401) {
			uni.navigateTo({
				url: "/pages/mine/login?interceptors=1"
			});
		} else if (code === 403) {
			uni.showToast({
			    title: '没有权限',
			    icon: "none",
			});
			return Promise.reject(err);
		} else {
            uni.showToast({
                title: err.response.data.message,
                icon: "none",
            });
            return Promise.reject(err);
        }
    }
)
export default fly;

5、添加api 接口配置,在utils文件夹中新建api.js,引入Fly

import fly from './request'

export default {
    // 新增一条打卡记录
    addCheck: (params) => {
        return fly.post('/check/add', params);
    },
    // 获取用户信息
    getUser: () => {
        return fly.get('/user/get');
    },
     // 查询点赞的用户
    getLikeUsers: (params) => {
        return fly.get('/user-like-check/getUsers?id=' + params);
    },
    ...
}

6、挂载api到全局,在main.js中引入挂载

import API from "./utils/api.js"
Vue.prototype.$api = API

7、调用接口

let params = {
    // 评论文本
    content: this.content,
    groupId: this.curGroup,
};
this.$api.addCheck(params).then(res => {
         console.log(res)
    })
    .catch(err => {
        console.log(err)
    });

// 调用获取用户信息接口
this.$api.getUser().then(res => {
    console.log(res)
}).catch(err => {
    console.log(err)
})

你可能感兴趣的:(uni-app,微信小程序,小程序)