receiveParameters() 在 ktor 中失败

问题描述 投票:0回答:1

ktor
应用程序中,我尝试读取这样的发布参数:

val params = call.receiveParameters()

但是我面临这个错误:

No Default Transformations found for class io.ktor.utils.io.ByteBufferChannel and expected type TypeInfo(type=class io.ktor.http.Parameters, reifiedType=interface io.ktor.http.Parameters, kotlinType=io.ktor.http.Parameters) for call /...
io.ktor.server.plugins.BadRequestException: Failed to convert request body to class io.ktor.http.Parameters

我正在使用

ktor 3.0.0-beta-1
,我也安装了这样的内容协商:

install(ContentNegotiation) {
    gson {}
    json(Json {
            prettyPrint = true
            isLenient = true
            ignoreUnknownKeys = true
        })
}

我正在向应用程序发送POST请求,如下所示(使用Axios)

axios.post(
    `http://127.0.0.1:8080/api/...`,
    {
    a:"1",
    b:"2"
  },{})

由于我发送简单的字符串键和值对,因此我暂时使用以下解决方案,并且它有效:

 val paramsMap = call.receive<Map<String,String>>()

解决这个问题的正确方法是什么!?

kotlin serialization ktor content-negotiation
1个回答
0
投票

receiveParameters
用于读取表单数据 -
application/x-www-form-urlencoded
multipart/form-data
。我对 axios 不太熟悉,但你发送的请求似乎只是
application/json

可在

此处
找到可使用 receiveParameters 接收的 HTTP 请求示例。

POST http://localhost:8080/signup
Content-Type: application/x-www-form-urlencoded

username=JetBrains&[email protected]&password=foobar&confirmation=foobar

要了解如何使用 axios 发送

x-www-form-urlencoded
,请参阅 这篇文章

如果您只想发送 JSON,使用

receive
是正确的方法。如果密钥不是动态的,还可以考虑为此请求编写
@Serializable data class
,而不是将其反序列化为
Map

© www.soinside.com 2019 - 2024. All rights reserved.