无法在Kotlin JS中使用Ktor客户端发布请求

时间:2020-07-12 06:11:04

标签: ktor kotlin-js ktor-client

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

public async Task<Guid> Handle(CreateUserCommand request, CancellationToken cancellationToken) 
        {                           
            var userEntity = new UserProfile
            {                   
                Name = request.Name,                         
            };
            _context.UserProfile.Add(userEntity);
            
            AddressMaster addressMaster = request.Address;
            
            _context.AddressMaster.Add(addressMaster);

            UserAddresses userAddresses = new UserAddresses 
            {
                AddressID = addressMaster.AddressID,
                UserID = userEntity.UserID
            };
            _context.UserAddresses.Add(userAddresses);                                                        

            await _context.SaveChangesAsync(cancellationToken);

            return userEntity.UserID;
        }

BlockquoteIllegalStateException {message_8yp7un $ _0:“发送正文失败。内容的类型为:类OwnerMapper,但预期为OutgoingContent。”,cause_th0jdv $ _0:null,堆栈:“captureStack↵Exception↵RuntimeException↵IllegalSta…↵↵↵↵↵ ↵↵↵↵↵↵↵↵↵↵↵↵promiseReactionJob@ [native code]“,名称:“ IllegalStateException”}

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

“无法为类OwnerMapper找到无参数的序列化程序。对于通用类(例如列表),请显式提供序列化程序。”

我遵循了官方示例,但无法使其运行。我正在使用Kotlin / Js,并且上述错误来自浏览器。

2 个答案:

答案 0 :(得分:0)

您的OwnerMapper类是否标记为@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

答案 1 :(得分:0)

    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:选择适当的版本号。