简体   繁体   中英

How to get html, css and js all in one get with akka http?

I'm trying to serve my html, css and js with akka http:

path("") {
  get {
    getFromResourceDirectory("home")
    complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, home.render().toString()))
  }
}

home.render() is a twirl template that renders:

<html>
    <head>
        <link rel="stylesheet" href="home.css"> 
        <script src="home.js"></script>
    </head>
    <body>
        ...
    </body>
</html>

The html loads without problem except for the css and js files, this is my dir structure:

在此输入图像描述 and this error in chrome:

GET http://localhost:8080/home.js net::ERR_ABORTED
localhost/:5 GET http://localhost:8080/home.css net::ERR_ABORTED

In my project I solved it with getFromResource(path) method and additional route for resources:

val resourcePrefix = "pages"

get {
    pathSingleSlash {
      getFromResource("home.html")
    } ~
    path(resourcePrefix / Remaining) { resource =>
      getFromResource(resource)
    }
}

In your template file you would refer to resources like this:

<head>
    <link rel="stylesheet" href="/pages/home.css"> 
    <script src="/pages/home.js"></script>
</head>

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