2016-08-04 84 views
0

嘗試提交表單時,我總是收到405錯誤。這裏是我的控制器:Angular.js表單POST返回錯誤405方法不允許

'use strict';

angular. 
    module('myApp'). 
    component('zipPopup', { 
     templateUrl: 'zip-popup/zip-popup.template.html', 
     controller: function ZipPopupController($scope, $http) { 
      $scope.show = true; 
      $scope.hide = function(){ 
       $scope.show = false; 
      }; 
      $scope.user = {}; 
      $scope.regex = '\\d{5}'; 

      $scope.submitForm = function(isValid) { 
       if(isValid) { 
        $http({ 
         method : 'POST', 
         url  : '/leads', 
         data : $scope.user, 
         headers : {'Content-Type': 'application/x-www-form-urlencoded'} 
        }) 
        .success(function(response) { 
         $scope.show = false; 
        }) 
        .error(function(response) { 
         console.log(response); 
        }); 
       } 
      }; 
     } 
    }); 

繼承人我的觀點:

<div class="zip-popup text-center"> 
    <div class="popup-container"> 
     <form name="zipForm" class="zip-form" ng-submit="submitForm(zipForm.$valid)" novalidate> 
      <input ng-model="user.zipCode" ng-pattern="regex" name="zipCode" class="form-control text-center" placeholder="Your Zip" required /> 
      <p class="error" ng-show="zipForm.zipCode.$invalid && !zipForm.zipCode.$pristine">A 5 digit zip code is required.</p> 
      <button type="submit" class="btn btn-block" ng-disabled="zipForm.$invalid">Submit</button> 
     </form> 
    </div> 
</div> 

是否有不同的文件,或者說我需要修改,以允許這種情況發生些什麼呢?我錯過了什麼?

+0

確定鏈接是有效的。即'url:'/ leads''.Is this api call? –

+0

/潛在客戶可以在本地處理表格數據 – Dubster

回答

1

服務器告訴您的特定方法(GETPOSTPUTPATCHDELETE等)不能被所述服務器接受。這很可能是由於您的API路由/端點沒有配置POST方法。

例如,在ExpressJS你需要配置通過執行以下操作接受POST路線:

app.post('/leads', function (req, res) { 
    res.send('POST request to the homepage'); 
}); 

有關405 Method Not Allowed錯誤,click here更多信息。

+0

我想這是這樣的。我只是不確定如何配置路由來接受帶有Angular的POST。 – Dubster

+0

你已經在你的'$ http'請求中發送POST了。問題不在於角度,而在於您的API。您的API使用哪種語言或框架編寫? – Soviut

+0

這可能是實際的問題,我還沒有設置表單處理程序。 – Dubster

0

幾周前我有類似的問題。事實證明,服務器只接受標題中特定類型的'Content-Type'

但是改變Content-Type應用/ JSON解決問題:

$http({ 
    method : 'POST', 
    url  : '/leads', 
    data : $scope.user, 
    headers : {'Content-Type': 'application/json'} 
}) 
.success(function(response) { 
    $scope.show = false; 
}) 
.error(function(response) { 
    console.log(response); 
}); 

附:我並不是說這必將解決您的問題,但這是與此類問題相關的解決方案。只需找出您的服務器預期的輸入類型即可。


編輯

我不是說送'application/json'Content-Type。我要說的是,找到什麼類型的內容是可以接受的,併發送這種類型的頭。

+0

這將返回一個不同於'405方法不允許的錯誤'的錯誤。也許你正在考慮'406不可接受'? – Soviut

+0

我並不是說''application/json''就是'Content-Type'。我要說的是**找到可接受的內容類型併發送該類型的頭文件。** –

+1

無論內容類型是什麼,如果內容類型不被接受,它會給出406錯誤,而不是405. – Soviut

相關問題