微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

uniapp 手撕配置,拦截器简易版

1. 配置URL地址文件

项目根目录下生成一个文件config文件夹中生成一个 config.js 文件

module.exports = {
    dev:"www.xxxxxx.xxx",
    test:"www.xxxxxx.xxx",
    pro:"www.xxxxxx.xxx"
}

2. 请求拦截、响应拦截

项目根目录下生成一个文件utils文件夹中生成一个 request.js 文件

import config from "/config/config.js";

let baseUrl = config.test;

module.exports = {
	fetch: (url, data = {}, option = {}) => {
        
        // 请求前操作 -- 开始 --
		let {
			loading = true, toast = true, method = 'get'
		} = option;
        // 将token存放在了globalData,通过getApp().globalData获取, 注意将获得登录后获得的token存在globalData中。
        let header = {
            'content-type': 'application/x-www-form-urlencoded',
            'token':getApp().globalData.token
        };
        // 请求前操作 -- 结束 --
		return new Promise((resolve, reject) => {
			if (loading) {
				uni.showLoading({
					title: "加载中...",
					mask: true
				})
			};
			uni.request({
				url: baseUrl + url,
				data,
				method,
				header,
                // 响应操作  -- 开始 --
				success: function(result) {
					let res = result.data;
					if (res.code == 200) { // 根据后端返回的code值,对不同的状态做相应的处理;
						if (loading) {
							uni.hideLoading();
						}
						resolve(res);
					} else if (res.code == 203) {
						uni.redirectTo({
							url: '/login/login'
						})
					} else {
						if (toast) {
							uni.showToast({
								mask: true,
								title: res.msg,
								icon: 'none'
							})
						} else {
							uni.hideLoading()
						}
						resolve(res);
					}
				},
				fail: function(e = {
					code: -1,
					msg: errMsg,
					errMsg
				}) {
					console.log(e)
					let msg = e.errMsg;
					if (msg == "request:fail timeout") {
						msg = "请求超时,请稍后再试";
					} else if (msg == "request:fail" || msg == "") {
						msg = "请求失败,再试试"
					}
					uni.showToast({
						title: msg,
						icon: "none"
					})
					reject(e);
				}
                // 响应操作  -- 结束 --
			})
		})
	},
}

3. 引入文件

main.js 中引入写好的 request.js 文件

import Vue from 'vue'
import App from './App'
import request from "./utils/request.js";

Vue.prototype.get = request.fetch;
Vue.prototype.post = (url, data) => {
	return request.fetch(url, data, {
		method: "post"
	});
};
Vue.config.productionTip = false

App.mpType = 'app'

const app = new Vue({
    ...App
});

app.$mount()

4. 请求的方法 get 、post

直接调用 this.get() 或者直接调用 this.post() 就可以了

login() {
    let data={...};
    this.get("/api/login",data).then(res=>{
        console.log(res);
    })
    // or
    this.post("/api/login",data).then(res=>{
        console.log(res);
    })
}

有疑惑的小伙伴,可能是我表达不清楚,可以留言讨论,如有错误,也希望大家不吝指出。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐