当前位置:   article > 正文

uni-app 接口封装,token过期,自动获取最新的token_uniapp token过期自动登录

uniapp token过期自动登录

一、文件路径截图

        

2、新建一个文件app.js

  1. let host='http://172.16.192.40:8083/jeecg-boot/' //本地接口
  2. let myApi = {
  3. login: `${host}wx/wxUser/login`, //登录
  4. }
  5. module.exports = myApi

3、新建一个文件request.js
        

  1. import myApi from '@/utils/app.js';
  2. export const request = (options) => {
  3. console.log(options, `调用接口`)
  4. return new Promise((resolve, reject) => {
  5. const WXUSER = uni.getStorageSync('WXUSER');
  6. if (!options.url) return console.error('请传入URL')
  7. else sendRequest(options, resolve, reject);
  8. })
  9. };
  10. //封装的发送请求函数
  11. function sendRequest(options, resolve, reject) {
  12. const WXUSER = uni.getStorageSync('WXUSER');
  13. uni.request({
  14. url: options.url,
  15. data: options.data || '',
  16. method: options.method || 'POST',
  17. header: {
  18. "X-Access-Token": WXUSER.rememberToken, //传递的token
  19. },
  20. success: (res) => {
  21. if (res.data.code == 401) {
  22. console.log('返回401,token失效')
  23. wxlogin(options).then(() => {
  24. sendRequest(options, resolve, reject);
  25. });
  26. } else resolve(res.data)
  27. }
  28. })
  29. }
  30. //封装的登录 登陆成功后获取信息
  31. export async function wxlogin(options) {
  32. return new Promise((resolve, reject) => {
  33. uni.getUserInfo({
  34. success: (UserRes) => {
  35. uni.login({
  36. desc: 'weixin',
  37. success: res => {
  38. wx.request({
  39. url: myApi.login,
  40. method: 'POST',
  41. data: {
  42. weappCode: res.code,
  43. },
  44. success: res => {
  45. if (res.data.success) {
  46. console.log(res.data.result.wxUser)
  47. const WXUSER = res.data.result.wxUser
  48. const SYSUSER = res.data.result.sysUser
  49. uni.setStorageSync('WXUSER',WXUSER);
  50. uni.setStorageSync('SYSUSER',SYSUSER);
  51. resolve(); // 登录成功后,返回resolve
  52. } else {
  53. console.log('登录错误', res)
  54. reject(); // 登录失败时,返回reject
  55. }
  56. }
  57. });
  58. }
  59. });
  60. }
  61. })
  62. });
  63. }

4、页面使用
        

  1. <!-- 首页 -->
  2. <template>
  3. </template>
  4. <script>
  5. import myApi from '@/utils/app.js' //调用接口使用
  6. export default {
  7. components: {
  8. },
  9. data() {
  10. return {
  11. dataSource: [],
  12. };
  13. },
  14. onLoad() {
  15. this.loadData()
  16. },
  17. methods: {
  18. async loadData() {
  19. try {
  20. const res = await this.$request({
  21. url: myApi.CcrUgcList,
  22. method: 'GET',
  23. });
  24. console.log(res)
  25. if (res.code === 200) {
  26. this.dataSource = res.result.records
  27. }
  28. } catch (e) {
  29. // 失败执行
  30. console.log(`这个接口错误:${myApi.CcrUgcList}`)
  31. } finally {
  32. // 执行代码正确、报错都执行
  33. }
  34. },
  35. }
  36. };
  37. </script>
  38. <style lang="scss" scoped>
  39. </style>

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/weixin_40725706/article/detail/231337
推荐阅读
相关标签
  

闽ICP备14008679号