AngularJS $http.post request is canceled by Chrome

2019-07-15 09:13发布

问题:

I've been googling this for hours...

here's my angularJS code:

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 =(");
        });

    };
}]);

here's the accompanying 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>

No matter what I do, I end up with a POST request that gets cancelled. I've previously succeeded in logging in to /webapi/login with standard jQuery ajax code. The server is configured for AJAX, so there's no need for a urlencode header. The Payload looks correct, identical to the one that sent by jQuery ajax.

What might be the problem?

This is from Chrome developer/network:

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

回答1:

Angular will not preventDefault() if the action parameter is set. See here

For this reason, Angular prevents the default action (form submission to the server) unless the element has an action attribute specified.

You should probably also use ng-submit="login() on the <form> instead of ng-click, so that it will submit the form when the user presses Enter



回答2:

Try removing form's

action="/webapi/login"

and button's

type="submit"