responseInterceptors.js 2.0 KB
/**
 * 响应拦截
 * @param {Object} http 
 */
module.exports = (vm) => {
	uni.$u.http.interceptors.response.use((response) => {
		console.log(response);
		/* 对响应成功做点什么 可使用async await 做异步操作*/
		const statusCode = response.statusCode
		const data = response.data
		// 自定义参数
		const custom = response.config?.custom
		if (statusCode == 401) {
			var prepath = getCurrentPage();
			uni.setStorageSync('prepath', prepath);
			uni.redirectTo({
				url: '/pages/index/login'
			});
			return;
		} else if (statusCode != 200 &&statusCode != 100) { // 服务端返回的状态码不等于200,则reject()
			// 如果没有显式定义custom的toast参数为false的话,默认对报错进行toast弹出提示
			if (custom.toast !== false) {
				uni.$u.toast(data.message || data.msg)
			}
			// 如果需要catch返回,则进行reject
			if (custom?.catch) {
				return Promise.reject(data)
			} else {
				// 否则返回一个pending中的promise
				return new Promise(() => {})
			}
		}
		return Promise.resolve(data || {}) 
	}, (response) => {
		/*  对响应错误做点什么 (statusCode !== 200)*/
		switch (response.statusCode) {
			case 401:
				var prepath = getCurrentPage();
				console.log(prepath);
				uni.setStorageSync('prepath', prepath);
				uni.redirectTo({
					url: '/pages/index/login'
				});
				break;
			default:
				uni.$u.toast('请求失败')
				break;
		}
		return Promise.reject(response)
	})
}

const getCurrentPage = () => {
	var pages = getCurrentPages() //获取加载的页面
	var currentPage = pages[pages.length - 1] //获取当前页面的对象
	var url = currentPage.route //当前页面url
	var options = currentPage.options //如果要获取url中所带的参数可以查看options

	//拼接url的参数
	var urlWithArgs = url + '?'
	for (var key in options) {
		var value = options[key]
		urlWithArgs += key + '=' + value + '&'
	}
	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);

	wx.setStorageSync('perpath', urlWithArgs);
	return urlWithArgs;
}