Akka-Http加载css& js资源

时间:2016-12-16 07:49:07

标签: akka akka-http sca

我想使用类似http服务器的akka​​-http(例如tomcat或nginx服务器) 使用这个简单的代码可以从Web浏览器加载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>

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

如何解决这个问题?

2 个答案:

答案 0 :(得分:7)

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

import akka.http.scaladsl.model.StatusCodes

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

答案 1 :(得分:0)

您需要遵循指令

get {
  getFromResourceDirectory("admin")
}