0

我正在使用 Alamofire 与我的 API 进行通信,并且我正在使用 RequestInterceptor 来捕获未经授权的请求或刷新 JWT 令牌。当一切顺利时,完全没有问题,但是如果响应不好(400,401),Alamofire 会尝试刷新令牌并再次发送请求。有一个奇怪的行为,因为它失败并出现序列化错误:

[Request]: PUT https://my.url.com/unregistered?
    [Headers]:
        Content-Type: application/json
    [Body]:
        {"name":"user16","email":"dummy@gmail.com"}
[Response]:
    [Status Code]: 400
    [Headers]:
        Connection: keep-alive
        Content-Length: 51
        Content-Type: application/json
        Date: Sun, 19 Sep 2021 08:13:57 GMT
        Server: nginx
    [Body]:
        {"message": "User with same email already exists"}
        {"message": "User with same email already exists"}
[Network Duration]: 0.21983695030212402s
[Serialization Duration]: 0.0001439583720639348s
[Result]: failure(Alamofire.AFError.responseSerializationFailed(reason: Alamofire.AFError.ResponseSerializationFailureReason.decodingFailed(error: Swift.DecodingError.dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Garbage at end." UserInfo={NSDebugDescription=Garbage at end.}))))))

它基本上读了两次相同的答案,并告诉我它不是 JSON 可序列化的。我绝对确定服务器只返回一个像 JSON 这样的响应,完全奇怪的是,Alamofire 在任何时候都这样做,一旦它返回成功序列化的主体,第二次它在序列化时失败。这是我正在使用的代码:

func authorization<T: Decodable>(
        _ url: String,
        method: HTTPMethod = .get,
        parameters: Parameters? = nil,
        decoder: JSONDecoder = JSONDecoder(),
        headers: HTTPHeaders? = nil,
        interceptor: RequestInterceptor? = nil,
        withInterceptor: Bool = false
    ) -> Future<T, ServerError> {
        return Future({ promise in
            AF.request(
                url,
                method: method,
                parameters: parameters,
                encoding: JSONEncoding.default,
                headers: headers,
                interceptor: withInterceptor ? self : nil
            )
            .validate(statusCode: [200, 401])
            .responseDecodable(completionHandler: { (response: DataResponse<T, AFError>) in
                print(response.debugDescription)
                switch response.result {
                case .success(let value):
                    self.saveCookies(cookies: HTTPCookieStorage.shared.cookies)
                    promise(.success(value))
                case .failure(let error):
                    promise(.failure(self.createError(response: response.response, AFerror: error, AFIerror: nil, data: response.data)))
                }
            })
        })
    } 

此外,我尝试向验证添加多个状态代码,但没有任何帮助。

当我曾经.responseString有任何想法时,我只能看到一次响应,这也很奇怪。

4

0 回答 0