A M*_*A M 2 post scala http http4s
我有一个通过网络发送的 Post 请求,以获取与我使用 Http4s 的用户相关的数据。
在编写 HttpRoutes 时,我使用它来处理 POST 的情况,如下所示:
case req @ POST -> Root/ "posts" { "name": username, "friends": friends} =>
Run Code Online (Sandbox Code Playgroud)
thename和 thefriends是在请求正文中作为参数传递的属性。
然而,我似乎可以识别出一些语法错误'=>' expected but '{' found。
这是不正确的 Scala 语法。这是官方http4s 文档中的示例:
case req @ POST -> Root / "hello" / id =>
for {
// Decode a User request
user <- req.as[User]
// Encode a hello response
resp <- Ok(Hello(user.name).asJson)
} yield (resp)
Run Code Online (Sandbox Code Playgroud)
您正在通过“/hello”路线访问 API。然后请求被解码(解组)到User实例。例如,您可以使用 Circe JSON 库来解码请求中的内容:
import io.circe.generic.auto._
import io.circe.syntax._
import org.http4s._
import org.http4s.circe._
Run Code Online (Sandbox Code Playgroud)
id是一个路径变量。在这里,您也可以看看如何使用查询参数:https://http4s.org/v0.21/dsl。
Circe 编码器用于将User实例转换为响应的 JSON 内容。
Ok(Hello(user.name).asJson)
Run Code Online (Sandbox Code Playgroud)