首页 > 解决方案 > 无法解码客户对 Vapor Swift 发布请求的响应

问题描述

我正在使用 vapor swift 客户端发出发布请求。我的代码看起来像这样

 _req.client.post("https://oauth2.googleapis.com/token") { req in
    try req.content.encode( [
        "code": code,
        "grant_type": "authorization_code",
        "redirect_uri": "http://localhost:8080/googleAuth"
    ])
}.flatMapThrowing { response in
    try response.content.decode(AccessToken.self)
}.map{ json in
    print(json)
}

返回完整的flatMapThrowinghttp响应,但是当我尝试用它解码时,.map我得到一个零。

这是我从 flatMapThrowing 得到的响应

HTTP/1.1 200 OK
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Expires: Mon, 01 Jan 1990 00:00:00 GMT
Pragma: no-cache
Date: Fri, 23 Apr 2021 16:03:57 GMT
Content-Type: application/json; charset=utf-8
Vary: X-Origin
Vary: Referer
Server: scaffolding on HTTPServer2
X-XSS-Protection: 0
X-Frame-Options: SAMEORIGIN
X-Content-Type-Options: nosniff
Alt-Svc: h3-29=":443"; ma=2592000,h3-T051=":443"; ma=2592000,h3-Q050=":443"; ma=2592000,h3-Q046=":443"; ma=2592000,h3-Q043=":443"; ma=2592000,quic=":443"; ma=2592000; v="46,43"
Accept-Ranges: none
Vary: Origin,Accept-Encoding
Transfer-Encoding: chunked

{
  "access_token": "...",
  "expires_in": 3599,
  "refresh_token": "...",
  "scope": "...",
  "token_type": "Bearer",
  "id_token": "..."
}

但是当我尝试用这个模型解码它时,我得到了一个空的 var

import Fluent
import Vapor

struct AccessToken: Content {
    var access_token: String
    var expires_in: String?
    var refresh_token: String?
    var scope: String?
    var token_type: String?
    var id_token: String?
}

标签: swiftvapor

解决方案


As told by Nick, the model had an error in the expires_in: String?, I decoded the json changing my model to:

import Fluent
import Vapor

struct AccessToken: Content {
    var access_token: String?
    var expires_in: Int?
    var refresh_token: String?
    var scope: String?
    var token_type: String?
    var id_token: String?
}

推荐阅读