【问题标题】:AngularJS $http.post request is canceled by ChromeAngularJS $http.post 请求被 Chrome 取消
【发布时间】:2014-10-31 23:55:16
【问题描述】:

我已经在谷歌上搜索了好几个小时...

这是我的 angularJS 代码:

var FrontControllers = angular.module('FrontControllers', [] );

FrontControllers.controller('LoginController', ['$scope', '$http', function($scope, $http){

    $scope.user = {};

    $scope.login = function() {
        console.log($scope.user);
        $http({
            url: '/webapi/login',
            method: 'POST',
            data: $scope.user
        }).success(function (data) {
            alert("success!");
        }).error(function(data) {
            alert("failed =(");
        });

    };
}]);

这是随附的 html

<div ng-controller="LoginController" id="login" class="box">

    <form novalidate role="form" action="/webapi/login" id="loginForm">                   
        <label for="signin" class="sr-only">Email or Username</label> 
        <input ng-model="user.username" type="text" autofocus class="form-control input-lg" id="username" name="username" size="20" placeholder="email or username">

        <label for="password" class="sr-only">Password</label> 
        <input ng-model="user.password" type="password" class="form-control input-lg" id="password" name="password" size="10" placeholder="password">

       <button ng-click="login()" type="submit" class="btn btn-lg btn-bright btn-block">Login</button>
    </form>

</div>

无论我做什么,我都会收到一个被取消的 POST 请求。我以前使用标准的 jQuery ajax 代码成功登录到 /webapi/login。服务器为 AJAX 配置,因此不需要 urlencode 标头。 Payload 看起来是正确的,与 jQuery ajax 发送的相同。

可能是什么问题?

这是来自 Chrome 开发者/网络:

Provisional headers are shown
Accept:application/json, text/plain, */*
Content-Type:application/json;charset=UTF-8
Origin:http://ec2-54-86-242-50.compute-1.amazonaws.com
Referer:http://ec2-54-86-242-50.compute-1.amazonaws.com/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.104 Safari/537.36
X-DevTools-Emulate-Network-Conditions-Client-Id:BB96CDC3-AD63-D024-E814-4726DF4843D8

【问题讨论】:

    标签: angularjs http


    【解决方案1】:

    如果设置了action 参数,Angular 将不会preventDefault()。见here

    因此,除非元素具有指定的操作属性,否则 Angular 会阻止默认操作(向服务器提交表单)。

    您可能还应该在&lt;form&gt; 上使用ng-submit="login() 而不是ng-click,以便在用户按Enter 时提交表单

    【讨论】:

    • 谢谢!删除操作参数有效。 (我真的可以吻你。我花了 4 个小时试图让这种愚蠢的形式发挥作用。)
    • 感谢奥斯汀!我无法表达这种感受,但是当我从 html 页面中删除 action 关键字时,它对我有用。万分感谢! :)
    【解决方案2】:

    尝试删除表单的

    action="/webapi/login"
    

    和按钮的

    type="submit"
    

    【讨论】:

    • 这也很有效。我给另一个回复打了勾,因为它排在第一位。非常感谢!
    猜你喜欢
    • 2014-02-21
    • 1970-01-01
    • 2016-02-23
    • 2019-09-12
    • 1970-01-01
    • 1970-01-01
    • 2014-09-08
    • 1970-01-01
    • 2014-05-19
    相关资源
    最近更新 更多