Swift NSURLConnection响应返回500状态代码
我正在尝试连接到本地node.js服务器设置并验证用户。我一直得到500状态码,但我不知道我错过了什么。 我曾尝试从web浏览器中使用这些凭据访问服务器,但效果与预期一致 注意:我知道我必须使用NSURLSession而不是NSURLConnection,但是现在,我需要让它工作 这是我的密码Swift NSURLConnection响应返回500状态代码,swift,nsurlconnection,Swift,Nsurlconnection,我正在尝试连接到本地node.js服务器设置并验证用户。我一直得到500状态码,但我不知道我错过了什么。 我曾尝试从web浏览器中使用这些凭据访问服务器,但效果与预期一致 注意:我知道我必须使用NSURLSession而不是NSURLConnection,但是现在,我需要让它工作 这是我的密码 func signInUserWithDetails(userName:String,userPassword:String,serverURL:NSURL) { let credDic :[St
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;
} })
状态代码500表示服务器无法处理您的数据,并发生内部错误。这通常是由于HTTP消息编码不正确造成的,服务器无法捕获所有可能的错误 当查看您的代码时,您会立即发现: 您没有向服务器发送正确的
应用程序/x-www-form-urlencoded
编码数据。这可能是您的问题的主要原因。另一个原因可能是,它可能不是登录所需的PUT
,而是POST
方法
但在解释如何正确编码数据之前,我建议先了解服务器是否接受JSON作为内容数据(
application/JSON
)。如果是这样,正确地编码数据就容易多了:拥有一个JSON对象(变量credDic
),只需在NSData
容器中将其转换为UTF-8格式的JSON即可。然后,以字节为单位获取长度,相应地设置标题内容类型
和内容长度
。我有一个类似的问题,但在尝试使用应用程序/json包含内容类型后,问题得到了解决
示例:request.addValue(“application/json”,forHTTPHeaderField:“Content Type”)看起来服务器希望接收
“name”
属性,可能不是“user[name]”
@kelin,我尝试过更改它,不,这没有什么区别!此外,我有相同的字典被发送在一个obj-c版本的代码,它的工作很好!(尽管是一个更模块化的版本)@pavithramouli
,请您将该obj-c工作版本添加到问题中好吗?它可以提供线索。我检查了它是否需要PUT而不是POST,而且,我尝试将内容类型设置为'let charset=cfStringConvertEncodingToAnacharSetName(CFStringConvertNSStringEncodingToEncoding(NSUTF8StringEncoding))requestOrg.addValue(“application/x-www-form-urlencoded;charset=(charset)”,用于HttpHeaderField:“Content Type”),其内容长度取自jsondata.length…且结果相同:(“我甚至尝试将其从application/x-www-form-urlencoded更改为plain application/json..不起作用..注意:content typeapplication/x-www-form-urlencoded
没有字符集参数。它将被服务器忽略。服务器应采用UTF-8-除非您的客户端有表单。您需要检查API,并请联系web服务团队,了解如何设置参数。如前所述,最简单的方法是使用UTF-8中的序列化credDic
设置application/json
。注意:使用application/json
,您可以选择设置字符集参数。谢谢,您让我找到了正确的方向。我终于理解了什么是applIcing/x-www-form-urlencoded类型需要并构建了我的httpbody,所以它可以按预期工作!我现在正在精炼代码,以便按照credDic中的预期对密钥进行正确排序,以形成主体(有什么智能方法吗?)。然后我会将其发布在这里,以防以后对其他人有所帮助。
{"error":{"message":"Cannot read property 'name' of undefined","stack":"TypeError: Cannot read property 'name' of undefined\n at Object.exports.signIn [as handle] ( .......