[英]Sending string from Node.js (Express) server to iOS Swift 3
我正在嘗試為我的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
回斯威夫特這樣我就可以繼續采取進一步的行動。 如何檢查該回復? 喜歡:
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.}
PS:我也不是很熟悉請求代碼,所以如果它正好擺在我面前,那么請向我解釋代碼。 不好意思!
您的代碼示例建議您的客戶端期望其中包含屬性message
的json響應。 如果您從服務器使用resp.send('Success')
,則它將不是json對象。 這將是一個字符串。
如果這是您希望在服務器響應上顯示的內容,則應更新客戶端以將數據簡單地解析為字符串。 您可以使用String(data: data, encoding: .utf8)
,其中“ data”是響應中返回的內容。
但是,我建議您利用HTTP狀態代碼。 如果登錄失敗,則可以在服務器代碼中以422進行響應。 這可以通過resp.status(422).send('Some optional message')
。 然后客戶端需要做的就是檢查響應狀態。 而不是字符串比較。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.