2016-07-27 51 views
3

我將下面的curl命令:curl命令來的NSURLRequest斯威夫特

curl -X PUT -H "Authorization: Bearer 34kjsfhjbdjkh.jdhfds334jdshfksfs.kkjkjdsakjsd" -d "current_pwd=oldpassword&new_pwd1=newpassword&new_pwd2=newpassword" localhost:3000/updateDetails

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() 
    } 
} 

curl命令工作完全正常。 我使用node.js express框架來運行服務器。

var currentPwd = req.body.current_pwd; 
var newPwd1 = req.body.new_pwd1; 
var newPwd2 = req.body.new_pwd2; 

當通過curl命令發送時,服務器會收到密碼值。當請求通過iOS發送時,newPwd1值或三者中的任何一個都是未定義的。任何想法爲什麼?我錯過了什麼嗎?

更新:身體解析 Express 4的配置如下:

app.use(bodyParser.json()); 
app.use(bodyParser.urlencoded({ extended: false })); 

更新2: 這似乎是不可思議。當我試圖打印日誌使用curl命令請求體:請求體似乎是有效

{ current_pwd: 'oldPwd', 
    new_pwd1: 'newPwd', 
    new_pwd2: 'newPwd' } 

當日志被打印出來使用的是iOS的NSURLRequest我得到一個空體請求主體: {}

+0

如果您在創建NSMutableURLRequest之前執行print(「stringPost is \(stringPost)」)',那麼stringPost是否具有您期望的值? –

+0

是的。要發佈的字符串與curl命令中的字符串相同 –

+0

接收到'PUT'時,node.js的'req'結構中出現了什麼?任何有效和預期的事情? –

回答

0

我必須設置標頭字段'Content-type'的值。

request.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-type") 

即修復它。