2016-12-16 64 views
2

我想使用akka-http像http服務器(例如tomcat或nginx服務器)。
這個簡單的代碼可以從網頁瀏覽器加載html源代碼,但無法加載鏈接到html文件的其他源代碼。Akka-Http加載css&js資源

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") 
}