简体   繁体   English

Alamofire响应不匹配的请求

[英]Alamofire response not matching request

I am having an issue when making a POST request to my API via Alamofire, GETs work without issue, however whenever I make a POST when I check the response I get the results of the last GET. 通过Alamofire向我的API发出POST请求时遇到问题,GET可以正常工作,但是当我在检查响应时进行POST时,都会得到上一次GET的结果。

import Alamofire
import SwiftyJSON

class NetworkManager {
    static let sharedInstace = NetworkManager()

    let defaultManager: Alamofire.Manager = {
        let serverTrustPolicies: [String: ServerTrustPolicy] = [
            "homestead.app": .DisableEvaluation
        ]

        let configuration = NSURLSessionConfiguration.defaultSessionConfiguration()
        configuration.HTTPAdditionalHeaders = Alamofire.Manager.defaultHTTPHeaders

        return Alamofire.Manager(
            configuration: configuration,
            serverTrustPolicyManager: ServerTrustPolicyManager(policies: serverTrustPolicies)
        )
    }()
}

internal class ApiHelper {

    /**
     Get data from a target URL and return JSON data to be parsed

     - parameter targetURL: URL to pull data from
     - parameter success:   return data to the calling function
     - parameter failure:   return an error message to the calling function
     */
    private func getDataFromAPI(targetURL: String, success:(JSONData: JSON) -> (), failure:(message: String) -> ())  {

        NetworkManager.sharedInstace.defaultManager.request(.GET, targetURL).responseJSON { response in
            print(response.result)
            switch response.result {
            case .Success:
                if let jsonRaw = response.result.value {
                    let json = JSON(jsonRaw)

                    success(JSONData: json)

                }
            case .Failure(let error):
                print(error.localizedDescription)
                failure(message: error.localizedDescription)
            }
        }
    }

    /**
     Post data to the target URL and return errors as JSON data to be parsed

     - parameter targetURL:  URL to post to
     - parameter parameters: JSON data to post
     - parameter success:    return success message to the calling function
     - parameter failure:    return JSON data to the calling function with server error
     */
    private func postDataToAPI(targetURL: String, parameters: [String : AnyObject], success:() -> (), failure:(JSONData: JSON) -> ())  {

        NetworkManager.sharedInstace.defaultManager.request(.POST, targetURL, parameters: parameters, encoding: .JSON).responseJSON { response in
            debugPrint(response)

            success()
        }
    }


    /**
     Post an updated profile to the API

     - parameter parameters: JSON data to be posted
     - parameter success:    success callback
     - parameter failure:    JSON data of serverError
     */
    internal func postUpdateRequest(parameters: [String : AnyObject], success:() -> (), failure:(JSONData: JSON) -> ()) {
        let url = "https://homestead.app/profile/a/update"

        postDataToAPI(url, parameters: parameters, success: {
            success()
            }, failure: { JSONData in
                failure(JSONData: JSONData)
        })
    }

    /**
     Get all states from the API

     - parameter success: JSON data of all states
     - parameter failure: failure message
     */
    internal func getAllStates(success:(JSONData: JSON) -> (), failure:(message: String) -> ()) {
        let url = "https://homestead.app/api/state/all"
        getDataFromAPI(url, success:
            { JSONData in
                success(JSONData: JSONData)
            }, failure: { message in
                failure(message: message)
        })
    }
}

let api = ApiHelper()
api.getAllStates({ JSONdata in
    print(JSONdata)
    let params: [String : AnyObject] = ["name" : "Bob"]
    api.postUpdateRequest(params, success: { JSONdata in
        print("Success")
        }, failure: { message in
            print("Message")
    })
    }, failure: { message in
        print(message)
})

My code first gets the list of states and then posts an updated user profile. 我的代码首先获取状态列表,然后发布更新的用户配置文件。 My issue is in that when I get the response for that updated user profile, it includes the response from the earlier GET request that had already been completed. 我的问题是,当我收到更新后的用户配置文件的响应时,它包括来自先前已完成的GET请求的响应。 The POST goes through and the changes are made in the web services, but I have no indications in my response object. POST进行了,并且在Web服务中进行了更改,但是我的响应对象中没有任何指示。

I have confirmed the server does not return the list of states when making a POST request, it returns below when called manually from the browser: 我已经确认服务器在发出POST请求时不会返回状态列表,而是从浏览器手动调用时返回以下状态列表:

{
  "success": "Changes saved!"
}

I'm at a loss on why I am getting a response from an earlier request from my POST. 我不知道为什么我从POST的早期请求中得到响应。 Any thoughts? 有什么想法吗?

I figured this out. 我想通了。 It turned out I had to add "X-Requested-With": "XMLHttpRequest" to the requests header: 原来我必须在请求标头中添加“ X-Requested-With”:“ XMLHttpRequest”:

   configuration.HTTPAdditionalHeaders = [
            "X-Requested-With": "XMLHttpRequest"
        ]

Now I am getting the responses correctly from the server. 现在,我可以从服务器正确获取响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM