用户未登录访问链接,前端如何跳转登录页

在某些必须要登录才能操作的前端项目中,有时候我们用户会遇到这样的场景,首次访问收藏了地址,下次通过收藏的地址访问的时候登录已过期,请求接口的时候后端会返回重定向的地址,此时状态码为200,无法从状态码判断是否重定向:
 这时候可以在响应拦截器中添加判断 response.request.responseURL.match(response.config.url) 为null则跳转登录页。
(loginRedirect?linkUrl=" + window.location.pathname)是传给后端的参数,登录后返回当前页
service.interceptors.response.use(
  response => {
    console.log('response', response) // for debug
 // 判断是否
    let matchUrl = response.request.responseURL.match(response.config.url);
    if (matchUrl!=null) {
      return response.data;
    } else {
      // store.dispatch("LogOut").then(() => {
        window.location.href = "/login/loginRedirect?linkUrl=" + window.location.pathname;
      // });
    }
  },
  error => {
    return Promise.reject(error)
  }
)
posted @ 2022-04-21 14:34  ppy-web  阅读(864)  评论(0编辑  收藏  举报