Akka-Http加载css&js资源

Akka-Http load css&js resources

我想像 http 服务器一样使用 akka-http(例如 tomcat 或 nginx 服务器)。
使用这个简单的代码可以从网络浏览器加载 html 源,但不能加载链接到 html 文件的其他源。

import akka.actor.ActorSystem
import akka.http.scaladsl.Http
import akka.http.scaladsl.server.Directives._
import akka.stream.ActorMaterializer

import scala.io.StdIn

object MainRunner extends App {

  implicit val system = ActorSystem("mySystem")
  implicit val materializer = ActorMaterializer()
  implicit val ec = system.dispatcher

  val staticResources =
    get {
        path("admin") {
          getFromResource("admin/index.html")
        } ~ pathPrefix("admin") {
        getFromResourceDirectory("admin")
      }
    }

  val bindingFuture = Http().bindAndHandle(staticResources, "localhost", 8080)

  println(s"Server online at http://localhost:8080/\nPress RETURN to stop...")
  StdIn.readLine() // let it run until user presses return
  bindingFuture
    .flatMap(_.unbind()) // trigger unbinding from the port
    .onComplete(_ => system.terminate()) // and shutdown when done
}

这是我的 html 文件:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="main.css">
</head>
<body>
<h1>Admin area</h1>
</body>
</html>

并在浏览器中收到此错误: 这是目录结构:

如何解决这个问题?

您需要遵循以下指令

get {
  getFromResourceDirectory("admin")
}

您需要在访问静态资源路径时在路由中添加尾部斜杠。 redirectToTrailingSlashIfMissing 指令应该可以解决问题:

import akka.http.scaladsl.model.StatusCodes

val staticResources =
  (get & pathPrefix("admin")){
    (pathEndOrSingleSlash & redirectToTrailingSlashIfMissing(StatusCodes.TemporaryRedirect)) {
      getFromResource("admin/index.html")
    } ~ {
      getFromResourceDirectory("admin")
    }
  }