无法 post 在 kotlin js 中使用 ktor 客户端请求

Not able to post request using ktor client in kotlin js

我正在尝试发出 http post 请求,但由于我无法理解的原因而失败。

object KtorClient {
val client = HttpClient() {
    install(JsonFeature) {
        serializer = KotlinxSerializer()
    }
 }
}
suspend fun createOwner(url : String = "http://localhost:112/company/owner/register", ownerMapper: OwnerMapper) {
println(ownerMapper)
client.post<Unit>(url){
   body = ownerMapper
}
}

BlockquoteIllegalStateException {message_8yp7un$_0: "Fail to send body. Content has type: class OwnerMapper, but OutgoingContent expected.", cause_th0jdv$_0: null, stack: "captureStack↵Exception↵RuntimeException↵IllegalSta…↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵↵promiseReactionJob@[native code]", name: "IllegalStateException"}

添加序列化插件后,出现此错误:

"Can't locate argument-less serializer for class OwnerMapper. For generic classes, such as lists, please provide serializer explicitly."

我已经按照官方的例子做了,但是做不到运行。我正在使用 Kotlin/Js 以上错误来自浏览器。

你的 OwnerMapper class 标记为 @Serializable 了吗?

如果不是--请标记为@Serializable

如果是 - 请尝试在没有 Ktor 的情况下重现第二个问题 ("Can't locate argument-less serializer for class OwnerMapper. For generic classes, such as lists, please provide serializer explicitly.")。对我来说,这看起来是序列化的问题,可能缺少某些依赖项。

请也看看 github 问题:https://github.com/Kotlin/kotlinx.serialization/issues/278

    val client = HttpClient() {
        install(JsonFeature){
            serializer = KotlinxSerializer()
        }
    }
@Serializable
data class OwnerLoginMapper(
    val email: String? = null,
    val username: String? = null,
    val number: String? = null,
    val credential: String
)
@Serializable
data class Token(
    val token : String
)
var response = client.post<Token>(url){
    contentType(ContentType.Application.Json)
    body = ownerMapper
}
println(response.token)

添加这些依赖项:

implementation("io.ktor:ktor-client-json-js:1.3.2")
implementation("io.ktor:ktor-client-serialization-js:1.3.2")
implementation("org.jetbrains.kotlinx:kotlinx-serialization-runtime-js:0.20.0")

应用此插件:

    kotlin("plugin.serialization") version "1.3.70"

PS: 选择合适的版本号。