总所周知的原因,vue打包后的项目直接丢到Vert.x的webroot下导致路由丢失/404。
访问前端页面结果蹦出来个Resource Not Found,嘎嘎糟心。
以下是解决办法。
第一步。
给API/WebSocket等地址来个前缀。如/api/xxxxService/getXXXXX
第二步 改造StaticHandler,来一个正则匹配地址,目的是防止Get请求被StaticHanlder识别。
router.route()
.pathRegex(excludePathRegex)//这里是apiURL前缀正则如"(?!/(api|ws))/.*"
.method(HttpMethod.GET)
.handler(StaticHandler
.create(webRootLOC)//index.html位置
.setCachingEnabled(false)
.setDefaultContentEncoding("utf-8")
);
第三步,添加404处理,让刷新,直接访问页面时不会导致路由丢失。
router.errorHandler(404, ctx -> {
if (ctx.request().method() == HttpMethod.GET && ctx.request().uri().matches(apiRouteRegex)) {
ctx.reroute("/index.html");
} else {
ctx.json(new JsonObject().put("code", 404).put("msg", "页面走丢了哟~"));
}
});
大功告成!