AngularJs $http postsuccessCallback 导致页面重定向,即使服务器以 200 状态响应也

AngularJs $http post successCallback is causing the page to redirect even when the server responds with a 200 status

本文关键字:服务器 响应 状态 重定向 postsuccessCallback http AngularJs      更新时间:2023-09-26

我在agularjs中编写了一个简单的控制器来处理表单提交。表单是使用 ng-submit 提交的。

服务器正在成功处理发布请求并返回 http 状态 200。但是AngularJs使用POST方法再次调用当前页面URL,这导致服务器返回MethodNotAllowedException(Laravel 5.2)页面。

这是控制器代码。

app.controller('adminAddController', ['$scope', '$http', 'Page', function($scope, $http, Page){
    $scope.formData = {};
    $scope.processForm = function($event) {
        console.log($scope.formData);
        $http({
            method  : "post",
            url     : 'http://localhost:8000/api/blogs',
            data    : $scope.formData,  
        })
        .then(function successCallback(response) {
            console.log(response);
        }, function errorCallback(response) {
            console.log(response);
        });
    };
}]);

通常发生这种情况是因为您没有阻止表单的默认操作,因此在发送 Ajax 调用后,表单会正常提交,然后浏览器要么被重定向,要么根据表单提交重新加载页面。

如果添加:

$event.preventDefault();

对您的处理程序来说,这应该照顾它。

app.controller('adminAddController', ['$scope', '$http', 'Page', function($scope, $http, Page){
    $scope.formData = {};
    $scope.processForm = function($event) {
        // prevent default form submission
        $event.preventDefault();
        console.log($scope.formData);
        $http({
            method  : "post",
            url     : 'http://localhost:8000/api/blogs',
            data    : $scope.formData,  
        })
        .then(function successCallback(response) {
            console.log(response);
        }, function errorCallback(response) {
            console.log(response);
        });
    };
}]);

此外,根据角度文档,如果您的<form>元素没有 action 属性,则表单提交将被 angular 自动阻止。 您没有显示相关的表单 HTML,因此我们不知道这是否适用于您的情况。

尝试像这样更改

app.controller('adminAddController', ['$scope', '$http', 'Page', function($scope, $http, Page){
        $scope.formData = {};
        $scope.processForm = function($event) {
            console.log($scope.formData);
            $http.post('api/blogs', {data:$scope.formData})
            .then(function successCallback(response) {
                console.log(response);
            }, function errorCallback(response) {
                console.log(response);
            });
        };
    }]);

谢谢和干杯

因此,问题似乎并不像看起来那么难解决。

我从表单元素中删除了 action=" 属性,它开始按预期工作。