Reputation:
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": "[email protected]",
"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!
Upvotes: 0
Views: 1066
Reputation:
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")
Upvotes: 3
Reputation: 1318
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": "[email protected]"] , which is invalid.
You need to have this format - { email = "[email protected]"; password = "Dittoenbram1234!";}
For this
Replace this -
let parameters = [
"email": "[email protected]",
"password": "Dittoenbram1234!"
]
With this -
let parameters: NSDictionary = [
"email": "[email protected]",
"password": "Dittoenbram1234!"
]
Hope this will help you. :)
Upvotes: 0