简体   繁体   中英

vert.x Serve static files

I have the following 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());
              }
          }
      );
  }
}

My html file is:

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

I used "StaticHandler.create..." in order to serve all static files inside client folder. As you can understand, I want that once the server gets a GET request to "localhost:3000/hello", the client will get an HTML page, which will call app.js file.

Unfortunately, I can't do it. index.html is loaded and the browser can't load app.js.

It's important to note that index.html and app.js both are located exactly in the same path which is ${PROJECT_ROOT}/client.

The code, however, is located in: ${PROJECT_ROOT}/src/main/java/com/company.

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

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

Why don't you try something straight-forward like:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM