2016-12-16 6 views
2

httpサーバ(たとえば、tomcatまたはnginxサーバ)のようにakka-httpを使いたいです。
この単純なコードでは、WebブラウザからHTMLソースを読み込むことはできますが、HTMLファイルにリンクされている他のソースは読み込むことができません。Akka-Http load css&js resources

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

を必要としています。 redirectToTrailingSlashIfMissingディレクティブは、このトリックを行う必要があります。

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

あなたは静的リソースのパスを打ったときに、末尾にスラッシュを追加するために、あなたのルートが必要になります次のディレクティブ

get { 
    getFromResourceDirectory("admin") 
}