【发布时间】:2021-05-14 15:33:01
【问题描述】:
我有一个静态网页存储在我的 Vapor 服务器的 Public 文件夹中。它有一个 index.html 文件。但是,当我导航到 root (http://localhost:8080) 时,它会显示 Not found。
我需要做什么使根指向 index.html?
【问题讨论】:
标签: vapor
我有一个静态网页存储在我的 Vapor 服务器的 Public 文件夹中。它有一个 index.html 文件。但是,当我导航到 root (http://localhost:8080) 时,它会显示 Not found。
我需要做什么使根指向 index.html?
【问题讨论】:
标签: vapor
您可以创建一个中间件来处理这个问题。
import Vapor
final class IndexPageMiddleware: Middleware {
func respond(to request: Request, chainingTo next: Responder) -> EventLoopFuture<Response> {
// check if path is /
guard request.url.path == "/" else {
// otherwise pass to next responder
return next.respond(to: request)
}
// respond with index
let indexPath = request.application.directory.publicDirectory + "/index.html"
let response = request.fileio.streamFile(at: indexPath)
return request.eventLoop.makeSucceededFuture(response)
}
}
然后在configure.swift 中添加以下内容
app.middleware.use(IndexPageMiddleware())
【讨论】:
request 没有application 参数,我没有找到如何获取公共目录的路径。有什么想法吗?
DirectoryConfiguration.detect().publicDirectory,它会起作用,但最好将公共目录的路径存储到storage(有点缓存)中,以免每次都检测到该路径。
在 Vapor 3 上,添加回家路线对我有用。具体来说,我在routes.swift 中添加了这样的路由:
router.get { req -> Future<View> in
let dir = DirectoryConfig.detect()
let path = dir.workDir + "/Public/index.html"
return try req.view().render(path)
}
【讨论】:
对于蒸汽 4 ...
在 routes.swift 内部:
app.get { req -> EventLoopFuture<View> in
return req.view.render(app.directory.publicDirectory + "index.html")
}
这假设您的项目目录根目录中有一个“Public”文件夹,其中包含一个 index.html 文件。
另外,在 configure.swift 中:
app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))
构建项目,运行服务器,将浏览器指向 localhost:8080,你甚至不必指定 localhost:8080/index.html,它就可以了。
【讨论】: