Swift - POST 请求,使用 Vapor 3 发送 JSON

Joe*_*yPi 5 json http swift vapor

我在使用 Vapor 3 发送正文包含 JSON 的 POST 请求时遇到问题。我正在使用https://docs.postman-echo.com/来测试它,它使用发送的相同 JSON 进行响应。

我已查看此处的答案,但在编码和内容类型方面出现错误。

router.get("hooray") { req -> Future<View> in

  var postHeaders: HTTPHeaders = .init()
  postHeaders.add(name: .contentType, value: "application/json")
  postHeaders.add(name: .accept, value: "*/*")
  postHeaders.add(name: .acceptEncoding, value: "gzip, deflate")

  let oneField = singleGet(foo: "barfoobar")

  // { foo: "barfoobar" } - JSON string

  let encoder = JSONEncoder()
  encoder.outputFormatting = .prettyPrinted

  let jsonData = try encoder.encode(oneField)
  let jsonString = String(data: jsonData, encoding: .utf8)!
  let postBody = HTTPBody(string: jsonString)

  let httpReq = HTTPRequest(method: .POST, url: "/post")

  let httpRes = HTTPClient.connect(hostname: "postman-echo.com", on: req)
                  .flatMap(to: singleGet.self) { client in
                    req.http.headers = postHeaders
                    req.http.contentType = .json
                    req.http.body = postBody
                    return client.send(httpReq).flatMap(to: singleGet.self) { res in
                      return try req.content.decode(singleGet.self)
                    }
                  }

  return try req.view().render("test", httpRes)
}
Run Code Online (Sandbox Code Playgroud)
struct singleGet: Content {
    let foo: String
}
Run Code Online (Sandbox Code Playgroud)

我使用此代码得到了正确的响应,但我想知道当我重新编写代码以匹配此答案时,为什么会出现错误?

我已将标头和正文添加到请求中,并在闭包内将它们注释掉,但这种方式行不通。

let httpReq = HTTPRequest(method: .POST, url: "/post", headers: postHeaders, body: postBody)
Run Code Online (Sandbox Code Playgroud)