Angular.js表单POST返回错误405不允许使用方法

Angular.js Form POST Returns Error 405 Method Not Allowed

本文关键字:不允许 使用方法 错误 返回 js 表单 POST Angular      更新时间:2023-09-26

我在提交表单时一直收到405错误。这是我的控制器:

"严格使用";

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>

是否有其他文件或我需要修改的内容来允许这种情况发生?我错过了什么?

服务器告诉您服务器无法接受特定的方法(GETPOSTPUTPATCHDELETE等)。这很可能是因为API路由/端点没有配置POST方法。

例如,在ExpressJS中,您需要通过执行以下操作来配置接受POST的路由:

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

有关405 Method Not Allowed错误的更多信息,请单击此处。

几周前我也遇到过类似的问题。事实证明,服务器只接受标头中特定类型的'Content-Type'

然而,将Content-Type更改为application/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);
});

p.S.我并不是说这一定能解决你的问题,但这是一个与这类问题相关的解决方案。只需找出服务器期望的输入类型即可


编辑

我并不是说将'application/json'作为Content-Type发送。我想说的是找到可以接受的内容类型并发送该类型的标题

您尝试让后端工程师实现OPTIONS方法。

https://en.wikipedia.org/wiki/Cross-origin_resource_sharing#Preflight_example