【发布时间】: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)(webDir 是root)时,index.html 已加载但无法访问 css/js 文件。
【问题讨论】:
-
您可以尝试将
pathEndOrSingleSlash放入pathPrefix("test")。还将pathSingleSlash替换为pathEndOrSingleSlash用于根路由(显示hello world)以获得更好的模式匹配。 -
不幸的是,这对结果没有任何影响。并且文档说明使用
redirectToNoTrailingSlashIfPresent是首选方式(即使我不确定我是否正确使用 int)。