我正在尝试为我的 iOS 移动应用程序创建一个登录系统。我有一个使用 Swift 3 发送到我的 Node.js 服务器的请求:
@IBAction func loginBtn(_ sender: UIButton) {
//created NSURL
let requestURL = NSURL(string: loginURL)
//creating NSMutableURLRequest
let request = NSMutableURLRequest(url: requestURL! as URL)
//setting the method to post
request.httpMethod = "POST"
//getting values from text fields
let empNum = empTextField.text
let empPass = passTextField.text
//creating the post parameter by concatenating the keys and values from text field
let postParameters = "empNum=" + empNum! + "&empPass=" + empPass!;
//adding the parameters to request body
request.httpBody = postParameters.data(using: String.Encoding.utf8)
//creating a task to send the post request
let task = URLSession.shared.dataTask(with: request as URLRequest){
data, response, error in
if error != nil{
print("error is \(String(describing: error))")
return;
}
//parsing the response
do {
//converting resonse to NSDictionary
let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as? NSDictionary
print("myjson : \(String(describing: myJSON))")
//parsing the json
if let parseJSON = myJSON {
//creating a string
var msg : String!
//getting the json response
msg = parseJSON["message"] as! String?
//printing the response
print("message here: \(msg)")
}
} catch {
print("Error here: \(error)")
}
}
//executing the task
task.resume()
}
我得到一个 200 服务器端,但我希望能够将 res.send
一个 string
返回给 Swift,这样我就可以继续采取进一步的行动。我如何检查该响应?喜欢:
if response == "vaild" {
...
}else{
...
}
当我运行此代码时,我收到一条错误消息:
Error here: Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}
附言我也不太熟悉请求代码,所以如果它就在我面前,请向我解释一下代码。提前抱歉!!
最佳答案
您的代码示例表明您的客户需要一个包含属性 message
的 json 响应。如果您使用来自服务器的 resp.send('Success')
,它将不是 json 对象。它将是一个字符串。
如果这就是您想要的服务器响应,您应该更新您的客户端以简单地将数据解析为字符串。您可以使用 String(data: data, encoding: .utf8)
,其中“data”是响应返回的内容。
但是,我建议使用 HTTP 状态代码。在您的服务器代码中,如果登录不成功,您可以使用 422 进行响应。这可以通过 resp.status(422).send('Some optional message')
来完成。然后客户端你需要做的就是检查响应状态。而不是字符串比较。
关于ios - 从 Node.js (Express) 服务器发送字符串到 iOS Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45829060/