vert.x 提供静态文件

vert.x Serve static files

我有以下 Verticle class:

public class SendFileExample extends AbstractVerticle {

  public void start(Future<Void> fut) throws Exception {
      Router router = Router.router(vertx);
      router.route("/hello").handler(StaticHandler.create("client"));

      router.route("/hello").handler(routingContext -> {
          HttpServerResponse response = routingContext.response();
          System.out.println("Hello");
          response.sendFile("client/index.html");
      });

      vertx.createHttpServer().requestHandler(router::accept).listen(3000,
          result -> {
              if (result.succeeded()) {
                  fut.complete();
              } else {
                  fut.fail(result.cause());
              }
          }
      );
  }
}

我的 html 文件是:

<html>
<head>
    <title> hello </title>
</heade>
<body>
    <h1> Hello World </h1>
    <button> Hello </button>
    <script src="app.js"></script>
</body>
</html>

我使用 "StaticHandler.create..." 来为客户端文件夹中的所有静态文件提供服务。 如您所知,我希望一旦服务器收到对 "localhost:3000/hello" 的 GET 请求,客户端将获得一个 HTML 页面,该页面将调用 app.js 文件。

很遗憾,我做不到。 index.html 已加载,浏览器无法加载 app.js。

重要的是要注意 index.html 和 app.js 都位于完全相同的路径中,即 ${PROJECT_ROOT}/client。

但是,代码位于: ${PROJECT_ROOT}/src/main/java/com/company.

你为什么不尝试一些直截了当的事情:

 if (req.path().equals("/")) {
   res.sendFile("client/index.html");
 }else{
   res.sendFile( "client" + req.path() );
 }

您在定义静态处理程序时只是错过了星号:

router.route("/hello*").handler(StaticHandler.create("client"));