I was converting the following curl command:
curl -X PUT -H "Authorization: Bearer 34kjsfhjbdjkh.jdhfds334jdshfksfs.kkjkjdsakjsd" -d "current_pwd=oldpassword&new_pwd1=newpassword&new_pwd2=newpassword" localhost:3000/updateDetails
into a NSURLRequest
:
func updatePassword(passwordInfo : NSDictionary){
let urlString = generateURLString("/updateDetails")
if let url = NSURL(string: urlString) {
let currPwd = passwordInfo["currPwd"] as! String
let nPwd1 = passwordInfo["newPwd1"] as! String
let nPwd2 = passwordInfo["newPwd2"] as! String
var stringPost = "current_pwd=" + currPwd
stringPost += "&new_pwd1=" + nPwd1
stringPost += "&new_pwd2=" + nPwd2
let data = stringPost.dataUsingEncoding(NSUTF8StringEncoding)
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "PUT"
request.addValue("Bearer " + getSessionToken(), forHTTPHeaderField: "Authorization")
request.HTTPBody=data
let session = NSURLSession.sharedSession()
let task = session.dataTaskWithRequest(request){
(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
if let httpResponse = response as? NSHTTPURLResponse {
if httpResponse.statusCode == 200 {
if let responseData = data {
let json = JSON(data: responseData)
}
}
}
}
task.resume()
}
}
The curl command works perfectly fine. I'm using node.js express framework for running the server.
var currentPwd = req.body.current_pwd;
var newPwd1 = req.body.new_pwd1;
var newPwd2 = req.body.new_pwd2;
The password value is received on the server when sent through the curl command. When the request is sent through iOS, the newPwd1 value or any of the three is undefined. Any idea why? Am I missing something?
Update: Express 4 configuration for body parsing is as follows:
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
Update 2: This seems to be weird. When I tried to print the log for the request body using a curl command: the request body seems to be valid
{ current_pwd: 'oldPwd',
new_pwd1: 'newPwd',
new_pwd2: 'newPwd' }
When the log is printed out for the request body using iOS NSURLRequest I get an empty body: {}