【问题标题】:getFromDirectory not working in a akka-http routegetFromDirectory 在 akka-http 路由中不起作用
【发布时间】:2019-02-03 05:24:43
【问题描述】:

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

现在,我正在尝试使用下面的 akka-http 路由 (myRoute) 将这个文件夹托管在 localhost:8080/test。此外,我想在localhost:8080 托管一个hello-world 页面。我还希望带有斜杠的 URI 重定向到非斜杠的 URI(localhost:8080/test 应该等于 localhost:8080/test/)。

不知何故,我无法做到这一点。 hello-world 页面工作正常,但文件夹未托管。我得到的只是一条The requested resource could not be found. 消息(在 Chrome 中)。

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)webDirroot)时,index.html 已加载但无法访问 css/js 文件。

【问题讨论】:

  • 您可以尝试将pathEndOrSingleSlash 放入pathPrefix("test")。还将pathSingleSlash 替换为pathEndOrSingleSlash 用于根路由(显示hello world)以获得更好的模式匹配。
  • 不幸的是,这对结果没有任何影响。并且文档说明使用 redirectToNoTrailingSlashIfPresent 是首选方式(即使我不确定我是否正确使用 int)。

标签: scala akka akka-http


【解决方案1】:

我已将 redirectToTrailingSlashIfMissing 移至内部指令。它似乎做了你想要的。请注意webdirindex.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)
        }
      }
    )

【讨论】:

  • 很好,这行得通。 (webdir 也可以是相对路径)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-12-21
  • 1970-01-01
  • 1970-01-01
  • 2021-12-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多