2016-08-04 87 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

相关问题