前后端分离项目最常见问题就是前端的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!