Carlos
Carlos

Reputation: 1133

Make root point to static webpage in Vapor

I have a static web page stored in the Public folder of my Vapor server. It has an index.html file. However when I navigate to root (http://localhost:8080) it displays Not found.

What I need to do make root point to index.html?

Upvotes: 2

Views: 666

Answers (3)

Tim Sonner
Tim Sonner

Reputation: 306

For Vapor 4 ...

Inside routes.swift:

app.get { req -> EventLoopFuture<View> in
    return req.view.render(app.directory.publicDirectory + "index.html")
}

This assumes you have a "Public" folder in your project directory root with an index.html file inside.

Also, in configure.swift:

app.middleware.use(FileMiddleware(publicDirectory: app.directory.publicDirectory))

Build project, run server, and point a browser to localhost:8080, you don't even have to specify localhost:8080/index.html, it just goes.

Upvotes: 2

Carlos
Carlos

Reputation: 1133

On Vapor 3, adding a home route worked for me. Specifically, I added the route in routes.swift like this:

router.get { req -> Future<View> in
    let dir = DirectoryConfig.detect()
    let path = dir.workDir + "/Public/index.html"
    return try req.view().render(path)
}

Upvotes: 2

imike
imike

Reputation: 5656

You could create a middleware to handle this.

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)
    }
}

then in configure.swift add the following

app.middleware.use(IndexPageMiddleware())

Upvotes: 1

Related Questions