为了 POST 到我用 nodejs 编写的 REST API,我编写了以下内容。但是我在服务器端没有得到任何响应。
func login()
{
let u = UserDefaults.standard.value(forKey: "userIP")!
let url_to_login = "http://\(u)/users/authenticate"
let url:URL = URL(string: url_to_login)!
let request = NSMutableURLRequest(url: url)
let postDataString = "tag=name:example@hotmail.co.uk&password:password"
let postData:NSData = postDataString.data(using: String.Encoding.ascii)! as NSData
request.httpMethod = "POST"
request.httpBody = postData as Data
request.setValue("application/x-www-form-urlencoded; charset=utf-8", forHTTPHeaderField: "Content-Type")
print(url_to_login)
}
//button actions
@IBAction func Submit(_ sender: UIButton) {
login()
}
这个 POST 应该简单地发送两个标签作为 x-www-form-urlencoded 并获得一个 token 作为返回。我已经发布了其他方法,但是,这并不表示在服务器端执行任何操作。
提前致谢。
最佳答案
你发布的正文看起来不对
改为:
let postDataString = "tag=name:example@hotmail.co.uk&password:password"
试试这个:
let postDataString = "name=example@hotmail.co.uk&password=password"
注意:您将数据作为 charset=utf-8
发送,但将其转换为 String.Encoding.ascii
关于swift - 如何从 swift 3 将 x-www-form-urlencoded 发布到 REST api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41766329/