NSURLConnection 响应 returns 500 状态码

NSURLConnection response returns 500 Status Code

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

注意:我知道我必须使用 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] ( .......

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

查看您的代码时,您会立即明白:

您没有向服务器发送正确 application/x-www-form-urlencoded 编码的数据。这可能是您遇到问题的主要原因。另一个原因可能是,它可能不是 PUT,而是 sign-in.

所需的 POST 方法

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

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

示例:request.addValue("application/json",对于 HTTPHeaderField:"Content-Type")

客户端应用程序获得 HTTP 状态代码 500 以及消息“内部服务器错误”作为对 API 调用的响应。 500 内部服务器错误可能是由 Edge 中执行任何策略期间的错误或 target/backend 服务器上的错误引起的。

HTTP 状态代码 500 是一般错误响应。这意味着服务器遇到了阻止它完成请求的意外情况。当没有其他错误代码合适时,通常由服务器返回此错误