0

I'm new to Ktor, and I'm trying to build a backend that processes login credentials. I'm attempting to use the content negotiation feature to convert JSON into a native Kotlin object, but I keep getting an unsupported media type exception. Here is my code:

fun Application.main() {
    install(CallLogging)
    install(DefaultHeaders)
    install(ContentNegotiation) {
        register(ContentType.Application.Json, GsonConverter())
    }
    routing {
        get("/") {
            call.respondHtml {
                head {
                    title("Kotlin Webapp")
                    script {
                        type = ScriptType.textJScript
                        src = "main.bundle.js"
                    }
                }
                body {
                    div {
                        id = "root"
                    }
                }
            }
        }
        post("/login") {
            val credentials = call.receive<Credentials>()
            println(credentials)
        }
    }
}

data class Credentials(val username: String, val password: String)

And here is the incoming Json I am trying to convert, which I am sending via XMLHttpRequest:

{"username":"Jamdan2","password":"sometext"}

I have searched the web for answers, but could not find what I am doing wrong. Can anybody help?

Aidan Heller
  • 41
  • 1
  • 4

1 Answers1

2

For completeness, since my comment seems to have helped:

You need to be sure that the request's Content-Type header is set to the correct value, in this case, application/json, otherwise the server cannot be entirely sure what to do with the received content.

In requests, (such as POST or PUT), the client tells the server what type of data is actually sent.

xhr.setRequestHeader("Content-Type", "application/json");
Salem
  • 13,516
  • 4
  • 51
  • 70