NSURLConnection响应返回500状态代码

时间:2015-12-26 08:50:45

标签: swift nsurlconnection

我正在尝试连接到本地node.js服务器设置并对用户进行身份验证。我一直得到500状态代码,无法弄清楚我错过了什么。 我尝试使用这些凭据从Web浏览器访问服务器,它按预期工作。

注意:我明白我必须使用NSURLSession而不是NSURLConnection,但是现在,我需要让它工作。

这是我的代码,

func signInUserWithDetails(userName:String,userPassword:String,serverURL:NSURL) {
    let credDic :[String:String]=["user[name]":userName,
                                   "user[password]":userPassword ]
    self.httpMethod="PUT"
    self.httpPath="/account"
    self.expectedStatusCode=201

    self.actualStatusCode=NSNotFound
    self.requestUniqueIdentifier = NSUUID().UUIDString

    let urlComponents = NSURLComponents(URL: serverURL, resolvingAgainstBaseURL: false)!
    urlComponents.path = httpPath
    let formedURL = urlComponents.URL!
    var requestOrg = NSMutableURLRequest(URL: formedURL)

    requestOrg.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    requestOrg.addValue("application/json", forHTTPHeaderField: "Accept")
    requestOrg.HTTPMethod=self.httpMethod!

    print(requestOrg.allHTTPHeaderFields) // Output 1

    do{
        let theJSONData = try NSJSONSerialization.dataWithJSONObject(credDic,options: NSJSONWritingOptions.PrettyPrinted)
        let theJSONText = NSString(data: theJSONData,encoding: NSASCIIStringEncoding)

        requestOrg.HTTPBody = theJSONData;

        let tempD=try NSJSONSerialization.JSONObjectWithData(requestOrg.HTTPBody!, options: []) as? [String:String]
        print("\(tempD)")  //Output 2

    }catch let error as NSError {
        print(error)
    }

   connection = NSURLConnection(request: requestOrg, delegate: self, startImmediately: true)!
}

我只是打印出这个回复,

func connection(didReceiveResponse: NSURLConnection, didReceiveResponse response: NSURLResponse) {
    print("----------------------didReceiveResponse")
    self.response=response
    print("Response Received:"+"\(self.response)")
    let urlResponse:NSHTTPURLResponse = response as! NSHTTPURLResponse
    let responseCode=urlResponse.statusCode
    self.actualStatusCode=responseCode
}

我得到的结果是

Optional(["Accept": "application/json", "Content-Type": "application/x-www-form-urlencoded"])
Optional(["user[password]": "R", "user[name]": "R"])
----------------------didReceiveResponse
Response Received:Optional(<NSHTTPURLResponse: 0x7faba269d440> { URL:   http://localhost:3000/account } { status code: 500, headers {
Connection = "keep-alive";
"Content-Length" = 1464;
"Content-Type" = "application/json";
Date = "Sat, 26 Dec 2015 08:34:45 GMT";
"X-Powered-By" = Express;
} })

didReceiveData 会抛出此错误

{"error":{"message":"Cannot read property 'name' of undefined","stack":"TypeError: Cannot read property 'name' of undefined\n    at Object.exports.signIn [as handle] ( .......

2 个答案:

答案 0 :(得分:2)

状态代码500表示服务器无法处理您的数据并遇到内部错误。这通常是由不正确编码的HTTP消息引起的,其中服务器无法捕获所有可能的错误。

查看代码时,会立即显现:

您没有向服务器发送正确的application/x-www-form-urlencoded编码数据。这可能是您问题的主要原因。另一个原因可能是,登录时可能不是PUT而是POST方法。

但在解释您如何正确编码数据之前,我建议您了解您的服务器是否接受JSON作为内容数据(application/json)。如果是这样,正确编码数据要容易得多:拥有一个JSON对象(您的变量credDic),只需将其转换为JSON,即NSData容器中的UTF-8。然后,获取字节长度,相应地设置标题Content-TypeContent-Length

答案 1 :(得分:0)

我遇到了类似的问题,但是在尝试使用 application / json 包含 Content-Type 后,此问题得以解决。

示例:request.addValue(“ application / json”,forHTTPHeaderField:“ Content-Type”)