将字符串从 Node.js(Express) 服务器发送到 iOS Swift 3



我正在尝试为我的iOS移动应用程序创建一个登录系统。我有一个请求发送到我的 Node.js 服务器与 Swift 3 一起:

@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 的服务器端,但我希望能够将stringres.send回 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)其中"数据"是从响应返回的内容。

但是,我建议利用HTTP状态代码。在服务器代码中,如果登录不成功,您可以使用 422 进行响应。这可以通过resp.status(422).send('Some optional message').然后客户端您需要做的就是检查响应状态。而不是字符串比较。

最新更新