代码之家  ›  专栏  ›  技术社区  ›  Florian Baierl

GetFromDirectory不在AKKA HTTP路由中工作

  •  0
  • Florian Baierl  · 技术社区  · 7 年前

    我有一个文件夹 root 包含一个 index.html 以及其他资源,如 .css 文件夹。

    现在,我正在尝试在托管此文件夹 localhost:8080/test 使用AKKA HTTP路由( myRoute )以下。另外,我想在 localhost:8080 . 我还希望带有尾随斜杠的URI重定向到非斜杠的URI( 本地主机:8080/测试 应该等于 localhost:8080/test/ )

    不知何故,我无法做到这一点。Hello World页工作正常,但文件夹未托管。我得到的只是一个 The requested resource could not be found. 信息(铬合金)。

    def route: Route = {
      redirectToNoTrailingSlashIfPresent(StatusCodes.Found) {
        (pathSingleSlash {
          get {
            complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, homeHtml)) // "hello world"
          }
        }
        ~
          pathPrefix("test") {
               getFromDirectory("root") // contains the index.html
        })
      }
    }
    

    编辑:

    当我尝试使用 getFromFile(webDir + "/index.html") 而不是 getFromDirectory(webDir) ( webDir 存在 根 ) 索引文件 已加载,但无法访问css/js文件。

    1 回复  |  直到 7 年前
        1
  •  1
  •   Alexey Novakov    7 年前

    我已经搬家了 redirectToTrailingSlashIfMissing 到内部指令。它似乎是你想要的。请注意 webdir 是文件夹的绝对路径 index.html

    val webdir = "/Users/<your_absolute_path>/root"
      val homeHtml = "homeHtml"
      def route =
        concat(
          pathSingleSlash {
            get {
              complete(HttpEntity(ContentTypes.`text/html(UTF-8)`, homeHtml)) // "hello world"
            }
          },
          (get & pathPrefix("test")) {
            (pathEndOrSingleSlash & redirectToTrailingSlashIfMissing(StatusCodes.TemporaryRedirect)) {
              getFromFile(s"$webdir/index.html")
            } ~ {
              getFromDirectory(webdir)
            }
          }
        )
    
    推荐文章