uniapp后端返回两个token,一个token过期,使用另一个token换取新token封装
时间: 2024-01-17 11:06:06 浏览: 96
可以在前端封装一个函数来完成这个过程。假设你的后端返回的数据格式如下:
```
{
"code": 200,
"msg": "success",
"data": {
"token1": "xxxxxx",
"token2": "yyyyyy"
}
}
```
可以使用以下代码来封装:
```js
function getToken() {
const token1 = uni.getStorageSync('token1')
const token2 = uni.getStorageSync('token2')
// 如果 token1 存在,则返回 token1
if (token1) {
return token1
}
// 如果 token2 不存在,则返回空字符串
if (!token2) {
return ''
}
// 向后端发送请求,使用 token2 换取新的 token1
uni.request({
url: 'http://example.com/refreshToken',
method: 'POST',
header: {
'Authorization': 'Bearer ' + token2
},
success(res) {
const newToken = res.data.token1
// 将新的 token1 存储到本地
uni.setStorageSync('token1', newToken)
// 删除旧的 token2
uni.removeStorageSync('token2')
return newToken
},
fail() {
// 如果刷新 token 失败,则返回空字符串
return ''
}
})
}
```
这个函数会先检查本地是否有 token1,如果有,则直接返回。如果没有 token1,则向后端发送请求,使用 token2 换取新的 token1,并将新的 token1 存储到本地。如果刷新 token 失败,则返回空字符串。在请求需要认证的接口时,只需要在请求头中添加 `Authorization: Bearer ${getToken()}` 即可。
阅读全文
相关推荐
![-](https://img-home.csdnimg.cn/images/20241231044955.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![-](https://img-home.csdnimg.cn/images/20241231045053.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![zip](https://img-home.csdnimg.cn/images/20241231045053.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![7z](https://img-home.csdnimg.cn/images/20241231044736.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![js](https://img-home.csdnimg.cn/images/20250102104920.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![-](https://img-home.csdnimg.cn/images/20241231044930.png)