通过拦截器,拦截接口如果返回token过期,请求接口获取新的token,拿新的token继续之前的请求。

//封装拦截器
import {
	requestURL_dev,
	requestURL_pro
} from '../config'

export default {
	config: {
		baseUrl: requestURL_dev,
		header: {
			'Content-Type':'application/json;charset=UTF-8',
			'Content-Type':'application/x-www-form-urlencoded'
		},  
		data: {},
		method: "GET",
		dataType: "json",  /* 如设为json,会对返回的数据做一次 JSON.parse */
		responseType: "text",
		success() {},
		fail() {},
		complete() {}
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		
		if (!options) {
			options = {}
		}
		options.baseUrl = options.baseUrl || this.config.baseUrl
		options.dataType = options.dataType || this.config.dataType
		options.url = options.baseUrl + options.url
		options.data = options.data || {}
		options.method = options.method || this.config.method
	   
		return new Promise((resolve, reject) => {
			let _config = null
			options.complete = (response) => {
				let statusCode = response.statusCode
				response.config = _config
				if (process.env.NODE_ENV === 'development') {
					if (statusCode === 200) {
						// console.log("【" + _config.requestId + "】 结果:" + JSON.stringify(response.data))
					}
				}
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				// 统一的响应日志记录
				_reslog(response)
				if (statusCode === 200 || statusCode === 401 || statusCode === 402) { //成功 ==>放开token过期 状态码
					resolve(response);
				} else {
					reject(response)
				}
			}

			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()

			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			
			// 统一的请求日志记录
			_reqlog(_config)

			if (process.env.NODE_ENV === 'development') {
				// console.log("【" + _config.requestId + "】 地址:" + _config.url)
				if (_config.data) {
					// console.log("【" + _config.requestId + "】 参数:" + JSON.stringify(_config.data))
				}
			}

			uni.request(_config);
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'  
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	}
}

/**
 * 请求接口日志记录
 */
function _reqlog(req) {
	if (process.env.NODE_ENV === 'development') {
		// console.log("【" + req.requestId + "】 地址:" + req.url)
		// if (req.data) {
		// 	console.log("【" + req.requestId + "】 请求参数:" + JSON.stringify(req.data))
		// }
	}
	//TODO 调接口异步写入日志数据库
}

/**
 * 响应接口日志记录
 */
function _reslog(res) {
	let _statusCode = res.statusCode;
	if (process.env.NODE_ENV === 'development') {
		// console.log("【" + res.config.requestId + "】 地址:" + res.config.url)
		// if (res.config.data) {
		// 	console.log("【" + res.config.requestId + "】 请求参数:" + JSON.stringify(res.config.data))
		// }
		// console.log("【" + res.config.requestId + "】 响应结果:" + JSON.stringify(res))
	}
	//TODO 除了接口服务错误外,其他日志调接口异步写入日志数据库
	switch(_statusCode){
		case 200:
			break;
		case 401:
			break;
		case 404:
			break;
		default:
			break;
	}
}


/**
 * 
 * 基于 Promise 对象
 */

import {
	getToken
} from '@/until/user.js'
import http from './http'
import store from '@/common/store/index.js';
module.exports = {
	request: (data) => {
		let url = data.url
		//设置请求前拦截器
		http.interceptor.request = (config) => {
			let storeToken = uni.getStorageSync("token");
			if (config.data.load) {
				//打开加载动画
				store.commit("setLoadingShow", true);
			}
			if (storeToken) {
				config.header.token = storeToken
			}
		}

		//设置请求结束后拦截器
		http.interceptor.response = async (res) => {
			store.commit("setLoadingShow", false);
			if (res.statusCode !== 200 && res.statusCode !== 401 && res.statusCode !== 402 && res.statusCode !== 403) { //响应成功关闭loading图标
				uni.showModal({
					title: "网络错误",
					content: res.errMsg,
					showCancel: false
				});
				return false;
			}

			if (res.data.code == 401 || res.data.code == 402) {
				return res.data = await doRequest(res, url)
			}
			if (res.data.code == 403) {
				store.commit("setLoadingShow", false);
				store.commit("emptyToken")
				uni.showToast({
					title: '账号在其他地方登录',
					icon: 'none',
					duration: 2000
				})
				setTimeout(() => {
					uni.navigateTo({
						url: '/pages/login/easyLogin/index'
					})
				}, 2000)
				return false;
			}
			return res;
		}
		return http.request(data)
	},
} //刷新token并继续之前请求
async function doRequest(response, url) {
	const res = await module.exports.request({
		url: '/sys/refreshToken',
		method: 'GET',
		data: {
			refreshToken: uni.getStorageSync("refreshToken")
		}
	})
	uni.setStorageSync('token', res.data.token);
	uni.setStorageSync('refreshToken', res.data.refreshToken);
	let config = response.config
	config.header.token = res.data.token
	var postData = {
		url: url,
		data: config.data,
		method: config.method
	}
	const resold = module.exports.request(postData)
	return resold
}

main.js


import api from '@/common/http/'
//全局请求
Vue.prototype.$api = api;

模块化api

import http from '../request'
export const test = (data) => {//测试接口
	return http.request({
		url: '/system/index',
		method: 'GET',
		data
	})
}

请求

async getYh(){
	try {
		let res = await this.$api.checkApi.getDictValueByType({
			type:'character'
		});
		if (res) {
			console.log(res)
		}
	} catch (e) {
		console.log(e)
	}
},
Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐