uni-app封装 uni.request请求及设置请求拦截

uni-app封装 uni.request请求及设置请求拦截

在pages文件同级下创建service目录,在此文件架里创建 index.js 和 request.js 文件和api文件夹

先设置请求拦截验证

index.js里的全部代码:

import Vue from 'vue'
import Request from './request.js'
const http = new Request();
// 此方法在request.js里用于更改基础请求路径
// console.log(http.setConfig()) 
http.setConfig((config) => {
	// console.log(config)
	var url=""
	// console.log(process.env.NODE_ENV)
	if(process.env.NODE_ENV === 'development'){
		url = '';
	}else{
		url = '';
	}
	config.baseUrl = url
	return config
})

http.interceptor.request((config, cancel) => {
	/* 请求之前拦截器 */
	uni.showLoading({
		title: "请稍后...",
		mask: true
	})
	var _token = uni.getStorageSync('setUserToken'); // 从本地缓存中同步获取指定 key 对应的内容。
	if (_token) {
		var token = {};
		if (typeof _token === 'string') {
			token = JSON.parse(_token);
		} else {
			token = _token;
		}
		if (token) {
			config.header.Authorization = token.token_type + ' ' + token.auth_token;
		}
	}
	return config;
})
http.interceptor.response(
	(response) => {
		/* 请求之后拦截器 */
		uni.hideLoading(); //关闭加载动画
		console.log(response);
		if (!response || response.statusCode == 401) {
			uni.clearStorage();
			uni.reLaunch({
				url: '/pages_package_login/login/login.vue',
			});
			return false;
		} 
		if (!response || response.statusCode == 404) {
			// console.log('123');
			uni.showToast({
				icon: 'none',
				position: 'bottom',
				title: '接口不存在'
			});
		} 
		else if (response.errMsg && response.errMsg == 'request:fail') {
			uni.showToast({
				icon: 'none',
				position: 'bottom',
				title: '网络连接失败'
			});
		} else {
			if (response.statusCode == 200 && response.data.statusCode == 200) {
				return response.data.data;
			} else {
				if (!response.data) {
					uni.reLaunch({
						url: '/pages_package_login/login/login.vue',
					});
				} else if (response.data.statusCode == 402) {
					uni.showModal({
						title: '提示',
						content: response.data.msg,
						showCancel: false
					});
				} else if (response.data.statusCode == 409) {
					uni.showModal({
						title: '提示',
						content: response.data.msg,
						showCancel: false
					});
				} else if (response.data.statusCode == 400) {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '非法操作'
					});
				} else {
					uni.showToast({
						icon: 'none',
						position: 'bottom',
						title: '系统错误'
					});
				}
			}
		}
	
	})
export {
	http
};

request.js 里的全部代码:

export default class Request {
	config = {
		baseUrl: '',
		header: {
			'Content-Type': 'application/json;charset=UTF-8'
		},
		method: 'GET',
		dataType: 'json',
		responseType: 'text',
		success() {},
		fail() {},
		complete() {}
	}

	static posUrl(url) { /* 判断url是否为绝对路径 */
		return /(http|https):\/\/([\w.]+\/?)\S*/.test(url)
	}

	interceptor = {
		request(f) {
			if (f) {
				Request.requestBeforeFun = f
			}
		},
		response(f) {
			if (f) {
				Request.requestComFun = f
			}
		}
	}

	static requestBeforeFun(config) {
		return config
	}

	static requestComFun(response) {
		return response
	}
	// 更改基础请求路径
	setConfig(f) {
		// console.log(f)
		// console.log(this.config)
		this.config = f(this.config)
	}

	request(options = {}) {
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = Request.posUrl(options.url) ? options.url : (options.baseUrl + options.url)
		options.data = options.data || {}
		options.header = options.header || this.config.header
		options.method = options.method || this.config.method
		return new Promise((resolve, reject) => {
			let next = true
			let _config = null
			options.complete = (response) => {
				let statusCode = response.statusCode
				response.config = _config
				response = Request.requestComFun(response)
				if (statusCode === 200) { // 成功
					resolve(response)
				} else {
					if (response)
						reject(response)
					else
						reject(null);
				}
			}
			let cancel = (t = 'handle cancel') => {
				let err = {
					errMsg: t,
					config: afC
				}
				reject(err)
				next = false
			}
			let afC = { ...this.config,
				...options
			}
			_config = { ...afC,
				...Request.requestBeforeFun(afC, cancel)
			}
			if (!next) return
			uni.request(_config)
		})
	}
	
	// 设置 get 和 post 请求 需要url请求地址 data所需参数 
	get(url, data, options = {}) {
		options.url = url
		options.data = data
		options.method = 'GET'
		// 使用 this.request 发起请求,传入参数,获取数据
		return this.request(options)
	}

	post(url, data, options = {}) {
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	}
}

封装api请求函数, 以了登录请求函数为例
在 api 文件夹里创建login.js

login里的全部代码:

/**
 * 首页api
 */
import {http} from '../index.js'


/**
 * 登录
 * @returns {Promise}
 */
export function getLogin(data){
	let config = {}
	let e = http.post("users/login",data,config);
    return e
}

然后在 main.js 引入挂载
main.js 里的全部代码:

import App from './App'
import Vue from 'vue'

import {http} from './service/index.js'
Vue.prototype.$http = http

Vue.config.productionTip = false
App.mpType = 'app'
const app = new Vue({
    ...App
})
app.$mount()

在页面中的应用:

import { getLogin } from '../../service/api/login.js'


getLogin('12345679812').then((res) => {
	console.log(res)
})
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值