Ben Lin
2024-06-18 9dfa701454d6a94690bad39dbb0e38f2a0b31489
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
43
44
45
46
47
48
<template>
  <PageWrapper
    title="登录过期示例"
    content="用户登录过期示例,不再跳转登录页,直接生成页面覆盖当前页面,方便保持过期前的用户状态!"
  >
    <Card title="请点击下面的按钮访问测试接口" extra="所访问的接口会返回Token过期响应">
      <CardGrid style="width: 50%; text-align: center">
        <a-button type="primary" @click="test1">HttpStatus == 401</a-button>
      </CardGrid>
      <CardGrid style="width: 50%; text-align: center">
        <span></span>
        <a-button class="ml-4" type="primary" @click="test2">Response.code == 401</a-button>
      </CardGrid>
    </Card>
  </PageWrapper>
</template>
<script lang="ts" setup>
  import { PageWrapper } from '@/components/Page';
  import { useUserStore } from '@/store/modules/user';
  import { sessionTimeoutApi, tokenExpiredApi } from '@/api/demo/account';
  import { Card } from 'ant-design-vue';
 
  defineOptions({ name: 'TestSessionTimeout' });
 
  const CardGrid = Card.Grid;
 
  const userStore = useUserStore();
  async function test1() {
    // 示例网站生产环境用的是mock数据,不能返回Http状态码,
    // 所以在生产环境直接改变状态来达到测试效果
    if (import.meta.env.PROD) {
      userStore.setToken(undefined);
      userStore.setSessionTimeout(true);
    } else {
      // 这个api会返回状态码为401的响应
      await sessionTimeoutApi();
    }
  }
 
  async function test2() {
    // 这个api会返回code为401的json数据,Http状态码为200
    try {
      await tokenExpiredApi();
    } catch (err) {
      console.log('接口访问错误:', (err as Error).message || '错误');
    }
  }
</script>