记录封装uni.request简单版本

44 阅读3分钟

配置环境变量(开发环境/生产环境/测试环境/......)

第1种方法:

let base_url = '';

if (process.env.NODE_ENV === 'development') {
	console.log('开发环境');
	base_url = 'https:xxxxxxxxx/api/xxx';
} else {
	console.log('生产环境');
	base_url = 'https:xxxxxxxxx/api/xxx';
}

// ......

第2种方法:

不想手动修改base_url就用这一种方法

npm init -y 生成 package.json文件,如果已有package.json文件,则跳过此步骤。

package.json文件中添加:


"uni-app": {
    "scripts": {
        "dev": {
            "title": "开发版",
            "env": {
                "UNI_PLATFORM": "mp-weixin",
                // 你的接口请求地址
                "VUE_APP_BASE_URL": "https://xxxxxx.com/api"
            }
        },
        "pre": {
            "title": "测试版",
            "env": {
                "UNI_PLATFORM": "mp-weixin",
                // 你的接口请求地址
                "VUE_APP_BASE_URL": "https://xxxxxx.com/api"
            }
        },
        "prod": {
            "title": "正式版",
            "env": {
                "UNI_PLATFORM": "mp-weixin",
                // 你的接口请求地址
                "VUE_APP_BASE_URL": "https://xxxxxx.com/api"
            }
        }
    }
}

完整的package.json:

{
    "name": "demo",
    "version": "1.0.0",
    "main": "main.js",
    "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
    },
    "keywords": [],
    "author": "",
    "license": "ISC",
    "description": "",
    "uni-app": {
        "scripts": {
            "dev": {
                "title": "开发版",
                "env": {
                    "UNI_PLATFORM": "mp-weixin",
                    // 你的接口请求地址
                    "VUE_APP_BASE_URL": "https://xxxxxx.com/api"
                }
            },
            "pre": {
                "title": "测试版",
                "env": {
                    "UNI_PLATFORM": "mp-weixin",
                    // 你的接口请求地址
                    "VUE_APP_BASE_URL": "https://xxxxxx.com/api"
                }
            },
            "prod": {
                "title": "正式版",
                "env": {
                    "UNI_PLATFORM": "mp-weixin",
                    // 你的接口请求地址
                    "VUE_APP_BASE_URL": "https://xxxxxx.com/api"
                }
            }
        }
    }
}

配置完成后,HBuilderX上方工具栏运行发行上会多出来刚才配置的三个模式

如下图所示:

1.png

2.jpg

运行 走的 development

发行 走的 production

使用环境变量

process.env.VUE_APP_BASE_URL

① 新建utils文件夹,新建url.js文件,当然,你也可以不建,随意,只是告诉你怎么用。

utils/url.js 内容:

export const base_url = process.env.VUE_APP_BASE_URL;

② 新建http文件夹,分别创建api.jsservice.js

api.js 用来存放所有API。

service.js 用来封装 uni.request

http/service.js内容:

import {
base_url
} from "../utils/url"; // 引用的上面配置好的 VUE_APP_BASE_URL,根据环境自动切换

export default (options) => { // 接受一个配置对象 {url:'xxx', method:'GET', //...}

    // 统一的请求头
    // 由于我这里除了登录之外,所有的请求都要带上token,所以我就直接写在这里了
    // Content-Type根据项目情况修改,请求方法"GET? POST? DELETE? PUT? get? post?"
    let header = {
        "token": uni.getStorageSync("token"),
        "Content-Type": "application/json; charset=utf-8",
        ...options.header // 允许自定义请求头, { header: {一些配置} } 可以重写 Content-Type
    }
    return new Promise((resovle, reject) => {
    
        // 友好提示,提示语句根据项目情况决定
        uni.showLoading({
            title: "请稍等"
        })
        uni.request({
            url: base_url + options.url, // 环境变量 + 配置项中的url = http:xxx + /api/list -> http:xxx/api/list
            method: options.method || "GET", // 请求方法
            header, // 请求头
            data: options.data || {}, // 请求参数
            success: (res) => {
                const {
                statusCode
                } = res;

                if (statusCode === 200) { // 根据接口返回的code码判定,开发者服务器定义的code码,不是http请求状态码
                    resovle(res.data);
                } else {
                    uni.clearStorageSync(); // 清缓存,可清可不清,具体看项目
                    switch (statusCode) {
                        case 401: // 什么码对应要做的事情,具体根据项目写
                        uni.showModal({
                            title: '提示',
                            content: "请登录",
                            showCancel: false,
                            success: () => {
                                setTimeout(() => {
                                    uni.navigateTo({
                                        url: '/pages/login/index'
                                    })
                                }, 600)
                            }
                        })
                        break;
                    default:
                        uni.showToast({
                            title: '请重试...'
                        })
                        break;
                  }
                }
            },
            fail: (error) => {
                if (error.errMsg.indexOf('request:fail') !== -1) {
                    // 带有'request:fail'字样的,统统提示网络异常
                    uni.showToast({
                        title: '网络异常',
                        icon: 'error'
                    })
                } else {
                    uni.showToast({
                        title: '未知异常',
                        icon: 'error'
                    })
                }
            },
            complete: () => {
                uni.hideLoading(); // 隐藏loading
                uni.hideToast(); // 隐藏消息提示
            }
        })
    })
}

http/api.js内容:

import request from './service.js'; // 上个文件默认暴露的方法

export const userLoginApi = (data) => {
	return request({ // <- 这个对象就是那个options配置对象
		url: "/user/login",
		method: "POST",
		data // <- 请求数据是由界面组件传递过来的
	})
}

export const submitOrderApi = (data) => {
	return request({
		url: "/index/buy",
		method: "POST",
		data
	})
}

export const getHomeListApi = (data) => {
	return request({
		url: "/index/index",
		method: "POST",
		data
	})
}

export const paymentApi = (data) => {
	return request({
		url: "/front/payment",
		method: "POST",
		data
	})
}

export const getOderListApi = (data) => {
	return request({
		url: "/index/selectOrderform",
		method: "POST",
		data
	})
}

在界面中使用 http/api.js中的方法

/pages/login/index.vue 登录页面:

import {
    userLoginApi
} from '@/http/api.js'

data() {
    return {
        user_info: {
            account: '账号',
            password: '密码',
            js_code: ''
        }
    }
},
methods:{
    submit() {
        // 准备账号、密码、验证码等登录接口需要的请求数据
        // 具体根据你自己的业务来写
        const that = this;

        uni.login({
            provider: "weixin",
            success: async (res) => {
                that.user_info.js_code = res.code; // 这个res.code是个啥? 用户登录凭证,用来换取openid和session_key等信息的
                
                // 所有请求参数准备完毕,发起请求
                const res = await userLoginApi(that.user_info);
                
                if(res.code === xxx) {
                    // 根据自己业务需求,判断code码做不同的事情
                }
            }
        })
    }
}

结束

封装的方法多种多样,有用 class 的,有用函数形式的,这只是其中一种写法,还要根据具体的项目需求去编写更契合自身项目的代码,这篇简易版的封装,我想更适合新手朋友看看,希望能帮助到大家,谢谢。