在 Vert.x Web 路由器上的不存在路由上提供静态 webroot/index.html 数据
Serve static webroot/index.html data on non-existing routes on Vert.x Web Router
场景:
- 我已将我的静态数据放在 webroot/* 文件夹位置和服务器上
根据要求提供这些数据。
- 我有很多路线可供路由APIs。
路由器代码:
Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
router.route("/api/login/account").handler((RoutingContext ctx) -> {
// Handler is here
});
router.route("/api/currentUser").handler(ctx -> {
// Handler is here
});
router.route().handler(StaticHandler.create());
router.route("/*").hanler(StaticHandler.create("webroot/index.html"));
文件夹 webroot 有以下文件:
- index.css
- index.html
- image/image.jpg
问题:
- 需要在路由不匹配时提供 webroot/index.html 文件 (它不起作用;返回值 **'Resource not found')* *:如果我请求 /xyz/abc 的数据,则应提供 webroot/index.html。
- 需要为其他静态文件提供请求参数(正在工作):如果我请求 /index.css 的数据,那么 webroot/index。 css 应该送达。
- 需要响应 API 请求的数据 (正在工作):如果我请求 /api/login/account 的数据,那么它应该响应。
我哪里漏了这里?解决方案是什么?
您应该添加最后一个处理程序,在一切都失败时发送您想要的文件。例如:
ctx.response().sendFile('webroot/index.html');
不要忘记添加您可能需要的 headers,例如缓存指令、位置、内容类型...
场景:
- 我已将我的静态数据放在 webroot/* 文件夹位置和服务器上 根据要求提供这些数据。
- 我有很多路线可供路由APIs。
路由器代码:
Router router = Router.router(vertx);
router.route().handler(BodyHandler.create());
router.route("/api/login/account").handler((RoutingContext ctx) -> {
// Handler is here
});
router.route("/api/currentUser").handler(ctx -> {
// Handler is here
});
router.route().handler(StaticHandler.create());
router.route("/*").hanler(StaticHandler.create("webroot/index.html"));
文件夹 webroot 有以下文件:
- index.css
- index.html
- image/image.jpg
问题:
- 需要在路由不匹配时提供 webroot/index.html 文件 (它不起作用;返回值 **'Resource not found')* *:如果我请求 /xyz/abc 的数据,则应提供 webroot/index.html。
- 需要为其他静态文件提供请求参数(正在工作):如果我请求 /index.css 的数据,那么 webroot/index。 css 应该送达。
- 需要响应 API 请求的数据 (正在工作):如果我请求 /api/login/account 的数据,那么它应该响应。
我哪里漏了这里?解决方案是什么?
您应该添加最后一个处理程序,在一切都失败时发送您想要的文件。例如:
ctx.response().sendFile('webroot/index.html');
不要忘记添加您可能需要的 headers,例如缓存指令、位置、内容类型...