简体   繁体   English

Swift POST请求不起作用

[英]Swift POST Request not working

I have this server set up with NodeJS that can receive a name and an email and let me know if they match.It can also let me know if the received data is not valid. 我使用NodeJS设置了该服务器,可以接收名称和电子邮件,并让我知道它们是否匹配,还可以让我知道接收到的数据是否无效。

This is my code in swift: 这是我的代码迅速:

func post() {
    let parameters = [
        "email": "windvaan@live.nl",
        "password": "Dittoenbram1234!"
    ]

    let url = NSURL(string: "http://localhost:3000/login")
    var request = URLRequest(url: url! as URL)

    request.httpMethod = "POST"

    guard let httpBody = try? JSONSerialization.data(withJSONObject: parameters, options: JSONSerialization.WritingOptions.prettyPrinted) else {
        return
    }

    request.httpBody = httpBody

    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let data = data {
            do {
                let json = try JSONSerialization.jsonObject(with: data, options: [])
                print(json)
            } catch {
                print(error.localizedDescription)
            }
        }
    }.resume()

}

When I call this function my server says that the data is not valid, but the data I put as the parameters is. 当我调用此函数时,服务器会说数据无效,但我作为参数输入的数据是有效的。 I believe it has something to do with this function and the parameters because my server is working fine. 我认为这与该功能和参数有关,因为我的服务器工作正常。 Thx in advance! 提前谢谢!

I figured it out, I had to add in this in my swift file: 我想通了,我不得不在我的快速文件中添加:

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

As per as your parameters value, it's not in valid JSON format. 根据您的参数值,它不是有效的JSON格式。 When you print your parameters value it will print - ["password": "Dittoenbram1234!", "email": "windvaan@live.nl"] , which is invalid. 当您打印参数值时,它将打印-[“” password“:” Dittoenbram1234!“,” email“:” windvaan@live.nl“],这是无效的。

You need to have this format - { email = "windvaan@live.nl"; 您需要使用以下格式-{email =“ windvaan@live.nl”; password = "Dittoenbram1234!";} 密码=“ Dittoenbram1234!”;}

For this 为了这

Replace this - 取代这个-

let parameters = [
       "email": "windvaan@live.nl",
       "password": "Dittoenbram1234!"
   ] 

With this - 有了这个 -

let parameters: NSDictionary = [
        "email": "windvaan@live.nl",
        "password": "Dittoenbram1234!"
    ] 

Hope this will help you. 希望这会帮助你。 :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM