【问题标题】:vert.x Serve static filesvert.x 提供静态文件
【发布时间】:2017-05-12 16:58:45
【问题描述】:

我有以下 Verticle 类:

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.

【问题讨论】:

    标签: java vert.x


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      你为什么不直接尝试一下:

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

      【讨论】:

      • 打印出路径并查看它们是否与您的文件匹配。您还可以检查文件是否存在
      • System.out.println( "path = " + req.path() );
      • 尝试不使用路由器。你之前的一个普通处理程序
      • 这可行,但正确的方法是对所有以“/hello”开头的路径使用静态处理程序。请参阅 Alexey 的回答。
      猜你喜欢
      • 1970-01-01
      • 2014-07-25
      • 1970-01-01
      • 2012-06-15
      • 2014-02-26
      • 2014-12-22
      • 2018-10-23
      • 2021-07-08
      • 2013-05-28
      相关资源
      最近更新 更多