实现代码
- 存储token:
uni.setStorageSync('token', res.data.result);
- 获取token:
uni.getStorageSync('token');
- 清除token:
uni.setStorageSync('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 {
uni.setStorageSync('token', res.data.result);
this.getUserInfo();
uni.switchTab({
url: '../list/list',
fail(e) {
console.error(e);
}
})
}
})
},
export const config = {
baseURL: "http://xxxx.com:8000/",
header: {
accessToken: uni.getStorageSync('token'),
contentType: "application/x-www-form-urlencoded",
}
};
globalInterceptor.response.use(
(res, config) => {
if (res.data.code === 401) {
uni.showToast({
title: '登录已失效,请重新登录',
icon: 'error',
duration: 2000
})
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);
}
);