我在使用Vapor 3发送带有JSON正文的POST请求时遇到问题。我正在使用https://docs.postman-echo.com/进行测试,它以与发送的JSON相同的方式返回。
我在here上查看了答案,但是在编码和内容类型上却出现了错误。
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
}
我用此代码得到了正确的响应,但是我想知道当我重新编写代码以匹配this answer时,为什么会出错?
我已将标头和正文添加到请求中,并在闭包内将它们注释掉,但这种方式行不通。
let httpReq = HTTPRequest(method: .POST, url: "/post", headers: postHeaders, body: postBody)