Hello! Noobie question, currently I'm learning Kt...
# ktor
r
Hello! Noobie question, currently I'm learning Ktor server and I want to redirect a call from a POST (
/token_verification
) endpoint to GET (
/authorized
) but seems that it returns a 405 because it's looking for
/authorized
with POST, does anyone know what could I be doing wrong? I'm using normal Routing (Not type-safe routing) Code and error in the thread 🧵
Error:
Copy code
2023-01-08 18:35:23.112 [eventLoopGroupProxy-4-2] INFO  Application - 405 Method Not Allowed: POST - /authorized
Code:
Copy code
import com.example.domain.model.Endpoint
import com.example.domain.model.UserSession
import io.ktor.server.application.call
import io.ktor.server.response.respondRedirect
import io.ktor.server.routing.Route
import <http://io.ktor.server.routing.post|io.ktor.server.routing.post>
import io.ktor.server.sessions.sessions
import io.ktor.server.sessions.set

fun Route.tokenVerificationRoute() {
    post(Endpoint.TokenVerification.path) {
        call.sessions.set(UserSession(id = "123", name = "SomeName"))
        call.respondRedirect(Endpoint.Authorized.path) // This path is GET but tries to make a POST
    }
}
j
You need to use an HTTP 303 redirect
r
Hey thanks for helping me here! Seems that I can't find any parameter to do that in
respondRedirect
, however, I found that inside it does a:
call.response.headers.append(Location, url)
to add the URL, then uses
respond(HttpStatusCode.CODE)
to return
301
or
302
Tried to do the same but instead added
303
, sadly I still got the same
405
error because it tries to use
POST
🤔
Copy code
fun Route.tokenVerificationRoute() {
    post(Endpoint.TokenVerification.path) {
        call.sessions.set(UserSession(id = "123", name = "SomeName"))

        call.response.headers.append(HttpHeaders.Location, Endpoint.Authorized.path)
        call.respond(HttpStatusCode.SeeOther)
    }
}
Wonder if I should append
XHttpMethodOverride
header and set it to
GET
, so the client knows that it must use
GET
instead of
POST
(I'm just shooting in the dark right now lol, I don't have any actual idea) or use other header
j
That's what a 303 tells the client. A 307 is used when you want the client to reuse the same HTTP method.
r
Oh got it now, but then why it tries to use
POST
when I just responded with
303
?
j
No idea. Client bug.
r
Could be, at least I know I'm on the right path, thank you for your time 😉
Alright found the 2 issues: • Using postman didn't work - switched to
Insomnia
, it worked! • When using browser, it was making a GET request to
/token_verification
instead of POST, that's why it also returned 405 Edit: Using the initial code works!