gpt4 book ai didi

swift - NSURLConnection 响应返回 500 状态码

转载 作者:搜寻专家 更新时间:2023-11-01 07:28:16 26 4
gpt4 key购买 nike

我正在尝试连接到本地 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,而是登录所需的 POST 方法。

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

关于swift - NSURLConnection 响应返回 500 状态码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34469834/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com