使根指向 Vapor 中的静态网页

问题描述

我有一个静态网页存储在我的 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)
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...