跟着JHipster学做项目 (8) 前后端分离项目刷新页面避免出现 white label

17 篇文章 0 订阅
16 篇文章 1 订阅

前后端分离项目最常见问题就是前端的router和后端的controller path之间的矛盾,这个矛盾在刷新页面时显露出来。通常页面跳转是交给前端router来控制,但是当页面刷新时,前端router的路径请求直接传递给后端,此时后端一定无法处理,因此转到white label报错页面。

之前Vue项目部署在Spring Boot出现页面空白问题的解决方案中提到将error page指向Vue的index.html页面,这个方案缺点很明显,NOT_FOUND请求将跳转至index.html, 而不是提供相应的信息。

JHipster通过前后端配合提供了一个更为妥善的方案。

首先在后端创建ClientForwardController为防止刷新跳转error page,

public class ClientForwardController {

    /**
     * Forwards any unmapped paths (except those containing a period) to the client {@code index.html}.
     * @return forward to client {@code index.html}.
     */
    @GetMapping(value = "/**/{path:[^\\.]*}")
    public String forward() {
        return "forward:/";
    }
}

在前端路由中,将"/"指向home page

    {
      path: '/',
      name: 'Home',
      component: Home
    },

也就是说利用类ClientForwardController重新将页面跳转控制权交还给前端router,而前端通过main.ts文件中给路由添加拦截器将真正没有匹配的页面跳转至not-found,而匹配的页面刷新后依旧跳转至原页面。

router.beforeEach((to, from, next) => {
  if (!to.matched.length) {
    next('/not-found');
  }

  if (to.meta && to.meta.authorities && to.meta.authorities.length > 0) {
    if (!accountService.hasAnyAuthority(to.meta.authorities)) {
      sessionStorage.setItem('requested-url', to.fullPath);
      next('/forbidden');
    } else {
      next();
    }
  } else {
    // no authorities, so just proceed
    next();
  }
});

Good Luck,

Cheers!

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值