问题描述
我有一个静态网页存储在我的 Vapor 服务器的公共文件夹中。它有一个 index.html 文件。但是,当我导航到 root (http://localhost:8080) 时,它会显示 Not found
。
我需要做什么才能让 root 指向 index.html?
解决方法
您可以创建一个中间件来处理这个问题。
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())
,
在 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)
}