简体   繁体   中英

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.

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. When you print your parameters value it will print - ["password": "Dittoenbram1234!", "email": "windvaan@live.nl"] , which is invalid.

You need to have this format - { email = "windvaan@live.nl"; password = "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. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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