2016-04-23 32 views
2

我有角度應用程序表單帖子的格式問題。下面是形式表格在角度js中無法正確發帖

   <form class="col s8 center"> 
        <h4> 
         {{greeting}} 
        </h4> 
        <div class="row"> 
        <div class="input-field col s12"> 
         <input id="email" type="email" class="validate" ng-model="user.email"> 
         <label for="email">Email</label> 
        </div> 
        <div class="input-field col s12"> 
         <input id="password" type="password" class="validate" ng-model="user.password"> 
         <label for="password">Password</label> 
        </div> 
        </div> 
        <div class="row"> 
         <div class="col s12"> 
         <input type="submit" class="waves-effect waves-light btn pink" style="width:100%" value="Login" ng-click="login(user)"> 
         </div> 
        </div> 
       </form> 

這裏的HTML代碼,我使用

$scope.login = function(user) { 
    console.log(user.email); 
    $http({ 
    url: baseDomain + 'auth/login/', 
    method: "POST", 
    data: user, 
    headers: { 
     'Content-Type': 'application/x-www-form-urlencoded' 
    } 
    }).then(function(response) { 
    $window.localStorage.token = response.data.token; 
    }, function(response) { 
    console.log(response); 
    }); 
}; 

現在函數正確調用角度登錄功能,但POST數據是像

{"password":"d","email":"[email protected]"}:"" 

什麼是相同的方法來做同樣的事情,我哪裏會出錯?

**編輯**

後數據從Firefox的開發工具檢查服用。

+0

我不明白問題出在哪裏。你的意思是說你的web api沒有收到請求? –

+0

它的格式不正確。看看發佈的數據,我想要的關鍵是用戶名和密碼。該應用程序使用'{「密碼」:「d」,「email」:「d @ s」}作爲整個 – georoot

+0

中的鍵,所以簡單地說$ _POST [「email」]是空的,但值在$ _POST [ '{「密碼」:「d」,「電子郵件」:「d @ s」}'] – georoot

回答

1

對於此application/x-www-form-urlencoded內容類型,您需要正確地將數據序列化爲「key = vale & key1 = value2」字符串。爲此,您可以使用內置的服務$httpParamSerializer

$http({ 
    url: baseDomain + 'auth/login/', 
    method: "POST", 
    data: $httpParamSerializer(user), 
    headers: { 
    'Content-Type': 'application/x-www-form-urlencoded' 
    } 
}) 
+0

它的工作表示感謝 – georoot

+0

是的,我上次嘗試過,顯然需要等一段時間,現在就做它:) – georoot

1

我想你應該參考這個解決方案:

https://stackoverflow.com/a/24964658/3351642

,其中指出

通過默認情況下,$ http服務會將傳出請求轉換爲 serializin g將數據作爲JSON,然後將其與內容- 類型「application/json」一起發佈。當我們想要將該值作爲FORM 發佈後,我們需要更改序列化算法並將數據 與內容類型「application/x-www-form-urlencoded」一起發佈。

,所以你應該這樣做:

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

雖然我很漂亮確定這個答案是正確的,但我去了上面的一個,因爲它更有效,我需要寫更少的代碼。但無論如何,我會給你一個upvote:D – georoot