uni-app 接口封装 微信小程序token 过期无痕获取


app.js页面

// 测试服务
// let host = "http://192.168.1.166:8823/jeecg-boot"
let myApi = {
	// 登录
	loginUrl: `${host}/wx/wxUser/login`,
	// 解密手机号
	getPhoneNo: `${host}/wx/wxUser/getPhoneNo`,
	// 增加设备
	
}
module.exports = myApi



request.js页面

import myApi from '@/utils/app.js';
export const request = (options) => {
	
	console.log("接口传值")
	console.log(options)
	return new Promise((resolve, reject) => {
		let token = uni.getStorageSync('token');
		if (!options.url) {
			console.error('请传入URL')
			return;
		}
		if (!token) {
			return
		}
		uni.request({
			url: options.url,
			data: options.data || '',
			method: options.method || 'POST',
			header: {
				"X-token": token,
			},
			success: (res) => {
				if (res.data.code == 401) {
					login();
				}
				if (res.data.code == 500) {
					login();
				}
				if (res.data.statusCode >= 500) {
					console.error('服务器错误,请检查接口')
				} else {
					resolve(res.data)
				}
			},
			fail: (res) => {
				// oken失效,提示
				resolve(res)

			}
		})
	})
};

// token 过期  自动获取新的token
export function login() {
	uni.login({
		desc: 'weixin',
		success: res => {
			wx.request({
				url: myApi.loginUrl,
				method: 'POST',
				data: {
					weappCode: res.code,
					weappWho:'WX_FACE'
				},
				success: res => {
					let token = res.data.result.wxUser.rememberToken
					uni.setStorageSync('token', token);
				}
			});
		}
	});
}



页面main.js引入
import { request } from '@/utils/request.js'


Vue.prototype.$request = request

文件夹如图

uni-app 接口封装 微信小程序token 过期无痕获取_第1张图片

import myApi from '@/utils/app.js'



loadDate() {
			let that = this
			let options = {}
			options.url = myApi.getIotAttenceRecdayslist
			options.method = 'GET'
			options.data = { attenceDay: that.ObjCalcDays.selectedDate }
			that.$request(options).then(res => {
				that.CalcDaysList = res.result.records
			})
		},

uni-app 接口封装 微信小程序token 过期无痕获取_第2张图片

你可能感兴趣的:(javascript,前端,开发语言)