问题描述
我通过网络发送了一个 Post 请求来获取与用户相关的数据 我为此使用了 Http4s。
在编写 HttpRoutes 时,我使用它来处理 POST 的情况,如下所示:
case req @ POST -> Root/ "posts" { "name": username,"friends": friends} =>
name
和 friends
是在请求正文中作为参数传递的属性。
然而,我似乎可以识别出一些语法错误'=>' expected but '{' found
。
解决方法
这是不正确的 Scala 语法。 以下是来自官方 http4s docs 的示例:
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)
您正在通过“/hello”路由访问 API。然后请求被解码(解组)到 User
实例。例如。您可以使用 Circe JSON 库从请求中解码内容:
import io.circe.generic.auto._
import io.circe.syntax._
import org.http4s._
import org.http4s.circe._
id
是路径变量。在这里,您也可以看看如何使用查询参数:https://http4s.org/v0.21/dsl。
Circe 编码器用于将 User
实例转换为响应的 JSON 内容。
Ok(Hello(user.name).asJson)