代码之家  ›  专栏  ›  技术社区  ›  Eric Kolotyluk

为什么Akka HTTP与我的JSON正文不匹配?

  •  0
  • Eric Kolotyluk  · 技术社区  · 6 年前

    我正在努力学习下面的例子 https://doc.akka.io/docs/akka-http/current/common/json-support.html

    我的代码看起来像

    final case class LeaderboardPostRequest(name: String, kind: String)
    final case class LeaderboardPostResponse(name: Option[String], id: String)
    
    trait JsonSupport extends SprayJsonSupport with DefaultJsonProtocol {
      implicit val requestFormat = jsonFormat2(LeaderboardPostRequest)
      implicit val responseFormat = jsonFormat2(LeaderboardPostResponse)
    }
    
    class LeaderboardEndpoint extends Directives with JsonSupport {
    . . .
      def leaderboardPost(name: Option[String]): Route =
        post {
          logRequest("leaderboard", Logging.InfoLevel) {
            entity(as[LeaderboardPostRequest]) { leaderboard =>
              try {
                complete(leaderboardCreate(Some(leaderboard.name), Some(leaderboard.kind)))
              } catch {
                case cause: LeaderboardException => complete(cause.getHttpResponse)
                case cause: Throwable =>
                complete(HttpResponse(InternalServerError, entity = s"Exception thrown from LeaderboardPost: ${cause.getMessage}"))
              }
            } ~
            complete(HttpResponse(BadRequest, entity = "****body missing****"))
        }
      }
    . . .
    }
    

    原木看起来像

    HttpRequest(HttpMethod(POST),http://localhost:8080/leaderboard?name=foo,List(User-Agent: Mozilla/5.0 (Windows NT; Windows NT 10.0; en-CA) WindowsPowerShell/5.1.17763.134, Host: localhost:8080, Timeout-Access: <function1>),HttpEntity.Strict(application/json,{name="foo",kind="ConcurrentLeaderboard"}),HttpProtocol(HTTP/1.1))
    

    但结果总是如此

     ****body missing****
    

    我怀疑这是件简单的事情,但我被阻止了,不知道需要什么额外的魔法。如有帮助/建议/提示,将不胜感激。

    1 回复  |  直到 6 年前
        1
  •  1
  •   Serhii Shynkarenko    6 年前

    我认为可能有几个(可能是交叉的)问题:

    1. 从我在日志消息中看到的情况来看 path 未配置路线的名称,请参考 path directive docs .

    2. 也许你误用了 logRequest 方法。参数值 "leaderbord" 只是一些日志标记,至少这是 logRequest directive docs

    3. 我不确定有效载荷本身是否正确: {name="foo",kind="ConcurrentLeaderboard"} LeaderboardPostRequest 案例类,根据 compose directive docs ,这是与 BadRequest