2016-09-15 33 views
0

我使用角$ http將數據發佈到來自cordova應用程序的節點應用程序。發佈的數據通過'body-parser'填充到req.body的KEY not VALUE中

我試了幾個「內涵式」,只有「應用/的X WWW的形式,進行了urlencoded」可以成功發送到節點服務器,所以我的代碼是這樣的:

$http({ 
     url: CONSTANTS.login_url, 
     method: "POST", 
     headers: { 
      'Content-Type': 'application/x-www-form-urlencoded' 
     }, 
     data: {"foo": "bar"}, 
     }) 

但在節點應用程序,我從req.body得到的數據是:

{"{"foo":"bar"}":""} 

身體的關鍵是一個字符串。

但我除外結果應該是像一個對象:

{ 
    "foo": "bar", 
} 

中有SO類似的問題,原因是他在前端使用「JSON.stringify」。但我不使用stringify爲什麼我不能得到例外數據?

+0

可能的重複[我如何POST $ urlencoded形式與$ http在AngularJS數據](http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with- http-in-angularjs) – str

回答

0

添加trnsformRequest功能轉換數據來匹配content-type

$http({ 
    url: CONSTANTS.login_url, 
    method: 'POST', 
    url: url, 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded' 
    }, 
    data: {"foo": "bar"}, 
    transformRequest: function(obj) { 
     var str = []; 
     for(var p in obj) 
     str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p])); 
     return str.join("&"); 
    } 
}).success(function() {}); 

回答here

希望這有助於借來的。

+0

是的,它的工作原理。非常感謝你。 – Glen

+1

@shakib最好將問題標記爲重複,而不是從別處複製答案。 – str