Is there a way to handle unresolved routes? I'm wr...
# ktor
l
Is there a way to handle unresolved routes? I'm writing an SPA that uses HTML5 history - which requires all unresolved routes to serve /
Given the way routing quality works, would /* be an appropriate way to handle this?
Copy code
status(HttpStatusCode.NotFound) {
            if(call.request.accept()?.contains("text/html", ignoreCase = true) == true) {
                val content = call.resolveResource("index.html", "static")
                if(content != null) call.respond(HttpStatusCode.OK, content)
            } else {
                call.respond(HttpStatusCode.NotFound, "Not found")
            }
        }
Is this the best way to do this?
w
So basically you are serving static html content and want to serve a 404 if the resource is not found?
a
l
@wilyarti not quite; actually the opposite. I use
defaultResource("index.html", "static")
for serving my
index.html
page on
/
, however, HTML5 history works by changing the URL client side. For example, my SPA may have a route for
/login
, however, this route is not present in ktor - the route only exists in Vue. HTML5 history requires that any paths that would have resulted in a 404, instead serve the
index.html
- so if a user were to refresh
/login
it ktor should just return
index.html
and Vue will handle the route accordingly. @avolkmann no dice,
file("{...}", "index.html")
in my
static {}
block I only see a 404 for routes undefined in ktor (e.g.
/noroute
). I tried your other suggestions, but I've so far been unsuccessful. The closest I've been able to get is this, but it just returns
index.html
for everything 😛 I hoped that the routing would have been smart enough to execute the tailcard last, but this doesn't seem to be the case.
Untitled
Something a bit like this; https://github.com/BrewdHQ/sparge
w
You could just match for a parameter. Like /{whatever}. Then just ignore the parameter and just server index.html as a static file via a redirect.