如何从 swift 3 将 x-www-form-urlencoded 发布到 REST API



我写了以下内容,以便发布到我用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-urlencoding 发送,并获得一个令牌作为回报。我已经发布了其他方法,但是,这也没有指示在服务器端执行任何操作。

提前谢谢。

你发布正文看起来不对

相反:

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

最新更新