CS456
CS456

Reputation: 117

how to POST x-www-form-urlencoded to REST api from swift 3

I have written the following in order to POST to a REST API I've written in nodejs. However I'm getting no response on the server side.

 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:[email protected]&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()
}

This POST should simply send the two tags as a x-www-form-urlencoded and get a token in return. I've POSTED other methods, however, this doesn't give an indication of doing anything on the server side either.

Thanks in advance.

Upvotes: 1

Views: 1544

Answers (1)

muescha
muescha

Reputation: 1539

you post body looks wrong

instead:

let postDataString = "tag=name:[email protected]&password:password"

try this:

let postDataString = "[email protected]&password=password"

Note: you send the data as charset=utf-8 but you convert it as String.Encoding.ascii

Upvotes: 2

Related Questions