【问题标题】:Make root point to static webpage in Vapor在 Vapor 中将根指向静态网页
【发布时间】:2021-05-14 15:33:01
【问题描述】:

我有一个静态网页存储在我的 Vapor 服务器的 Public 文件夹中。它有一个 index.html 文件。但是,当我导航到 root (http://localhost:8080) 时,它会显示 Not found

我需要做什么使根指向 index.html?

【问题讨论】:

    标签: vapor


    【解决方案1】:

    您可以创建一个中间件来处理这个问题。

    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.0。但是request 没有application 参数,我没有找到如何获取公共目录的路径。有什么想法吗?
    • 老实说,我几乎已经忘记了它是如何在 Vapor 3 中实现的。您可以尝试使用DirectoryConfiguration.detect().publicDirectory,它会起作用,但最好将公共目录的路径存储到storage(有点缓存)中,以免每次都检测到该路径。
    • 我无法回答这个问题。至少在 Vapor 3 上。我将在 Vapor 3 中发布一个对我有用的答案。无论如何,非常感谢 imike
    【解决方案2】:

    在 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有关
    【解决方案3】:

    对于蒸汽 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,它就可以了。

    【讨论】:

    • 在范围内找不到“应用”
    • 在 routes.swift 中,将代码放在 routes() 函数中,在 configure.swift 中,将代码粘贴到 configure() 函数中。 configure.swift 中的 app.middleware 调用实际上应该已经作为注释存在于文件中,只需取消注释该行。新路由,需要添加到 routes.swift routes() 函数中。那里应该已经有一些路线,只需模仿它们。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多