当前位置:   article > 正文

uniapp中token操作:存储、获取、失效处理。_uni.getstoragesync('token')

uni.getstoragesync('token')
实现代码
  1. 存储token:uni.setStorageSync('token', res.data.result);
  2. 获取token:uni.getStorageSync('token');
  3. 清除token:uni.setStorageSync('token', '');
应用场景
  • 在登录操作中,保存token
	pwdLogin() {
		....
				this.$axios.request({
					url: '.....',
					method: 'post',
					params: {
						username: this.username,
						password: this.password,
						...
					}
				}).then(res => {
					if (res.data.code !== 200) {
						uni.showToast({
							title: '登录失败',
							icon: 'error',
							duration: 2000
						})
					} else {
						// 保存 token
						uni.setStorageSync('token', res.data.result);
						// 保存用户信息到本地
						this.getUserInfo();
						// 登录成功  跳转结构物页面
						uni.switchTab({
							url: '../list/list',
							fail(e) {
								console.error(e);
							}
						})
					}

				})
			},
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 请求头中获取token携带
/**
 * 全局配置
 * 只能配置 静态数据
 * `content-type` 默认为 application/json
 * `header` 中`content-type`设置特殊参数 或 配置其他会导致触发 跨域 问题,出现跨域会直接进入响应拦截器的catch函数中
 */
export const config = {
	baseURL: "http://xxxx.com:8000/",
	header: {
		accessToken: uni.getStorageSync('token'),
		contentType: "application/x-www-form-urlencoded",
		// Content-Type: 'application/json'
		// 'Content-Type': 'application/json'
	}
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 响应拦截器中处理token失效
/**
 * 全局 响应拦截器, 支持添加多个拦截器
 * 例如: 根据状态码选择性拦截、过滤转换数据
 *
 * `return res` 继续返回数据
 * `return false` 停止返回数据,不会进入错误数据拦截,也不会进入catch函数中
 * `return Promise.reject('xxxxx')` 返回错误信息, 会错误数据拦截,也会进入catch函数中
 *
 * @param {Object} res 请求返回的数据
 * @param {Object} config 发送请求的配置数据
 * @return {Object|Boolean|Promise<reject>}
 */
globalInterceptor.response.use(
	(res, config) => {
		// token失效处理
		if (res.data.code === 401) {
			// 登录已失效,请重新登录
			uni.showToast({
				title: '登录已失效,请重新登录',
				icon: 'error',
				duration: 2000
			})
			//清空当前保存的token
			uni.setStorageSync('token', '');
			// 强制跳转至登录页
			uni.reLaunch({
				url: '/pages/login/login',
				fail(e) {
					console.error(e);
				}
			});
		}
		return res;
	},
	(err, config) => {
		console.error("is global response fail interceptor");
		console.error("err: ", err);
		console.error("config: ", config);

		return Promise.reject(err);
	}
);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/Cpp五条/article/detail/231300?site
推荐阅读
相关标签
  

闽ICP备14008679号