小程序传值给原生
- refresh_token :移动端接收类型
- ret 函数:监听移动端返回的数据
uni.sendNativeEvent('refresh_token', {
msg: 'unimp refresh_token'
}, ret => {
console.log('>>>app-refresh_token:' + JSON.stringify(ret));
if (ret != null && ret.isSuccess) {
let token = ret.token
uni.setStorageSync("token", token)
resolve(token)
} else {
reject("")
}
}
移动端传值给小程序
- isSuccess:数据是否正常返回;
- token:刷新后的 token 参数
{
"isSuccess":true,
"token":"bearer 475a2db1-00d4-4058-a8d2-77d5e33839dd"
}
UniApp 具体 js 源码
/* 请求之后拦截器。可以使用async await 做异步操作 */
http.interceptors.response.use(async (response) => {
console.log('>>>app-code-isReset:' + response.data.code == 401);
if (response.data.code == 401) { // token值过期
let newToken = await sendNativeReseive()
console.log('>>>app宿主App回传的数据-reseive:' + JSON.stringify(newToken));
let config = await doRequestConfig(response, newToken)
console.log('>>>app宿主App回传的数据-config:' + JSON.stringify(config));
const resetResponse = await http.request(config)
console.log('>>>app重新请求的数据-resetResponse:' + JSON.stringify(resetResponse));
if (resetResponse) {
response = resetResponse;
}
}
return response
}, (response) => { // 请求错误做点什么。可以使用 async await 做异步操作
console.log(response)
return Promise.reject(response)
})
/*同步 获取最新 token 值*/
var sendNativeReseive = function() {
return new Promise((resolve, reject) => {
uni.sendNativeEvent('refresh_token', {
msg: 'unimp refresh_token'
}, ret => {
console.log('>>>app-refresh_token:' + JSON.stringify(ret));
if (ret != null && ret.isSuccess) {
let token = "bearer " + ret.token
uni.setStorageSync("token", token)
resolve(token)
} else {
reject("")
}
})
})
}
/*同步 重新配置请求头的 token 值*/
var doRequestConfig = function(res, token) {
return new Promise((resolve, reject) => {
let config = res.config
config.header.Authorization = token
resolve(config)
})
}
文档更新时间: 2022-04-22 14:04 作者:陈冕