5

I have a problem sending a POST request with Vapor 3 with the body including JSON. I am using https://docs.postman-echo.com/ to test this, where it responds back with the same JSON it is sent.

I have viewed answers on here, but got errors with encoding and content types.

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)
}
struct singleGet: Content {
    let foo: String
}

I am getting the correct response with this code, but I was wondering when I rework the code to match this answer, why do I get errors?

I've added the headers and body to the request and comment them out inside the closure, but it won't work this way.

let httpReq = HTTPRequest(method: .POST, url: "/post", headers: postHeaders, body: postBody)
LuckyStarr
  • 1,468
  • 2
  • 26
  • 39
JoeyPi
  • 251
  • 3
  • 7

0 Answers0