简体   繁体   中英

Http POST request in AJAX works perfectly but not in AngularJS

I have problem with AngularJS. Im working on securing my Java Spring REST web application with Spring-Security. Im stuck on logging page - http post works perfectly using AJAX however it doesnt while using AngularJS.

jQuery(document).ready(function ($) {
    $('#login-form').submit(function (event) {
        event.preventDefault();
        var data = 'username=' + $('#username').val() + '&password=' + $('#password').val();
                console.log(data);
        $.ajax({
            data: data,
            timeout: 1000,
            type: 'POST',
            url: 'http://localhost:8080/OnlineGameStore/login'

        }).done(function(data, textStatus, jqXHR) {
            console.log("Done!")

        }).fail(function(jqXHR, textStatus, errorThrown) {
            alert('Booh! Wrong credentials, try again!');
        });
    });
    });

This AJAX code works perfectly, the credentials are properly send to the server. However:

angular.module('login').controller('LoginCtrl', function($scope, $http, $location, AuthUser ){

$scope.login = function(){
    AuthUser.authenticateUser( $scope.username, $scope.password, $location ).then( function(response){
        console.log(response);
    });

}; 
});

angular.module('login').service('AuthUser', function( $http, $location ){

    this.authenticateUser = function( username, password, $location ){ 
        var absUrl = $location.absUrl();
        console.log(absUrl);

        var data = {
            username: username,
            password: password
        };

        var config = {
                headers : {
                    'Content-type': 'application/json'
                }

        return $http.post(absUrl, data, config)
            .then(
                function(response){
                    return "Successfully logged!";
                },
                function(response){
                    window.alert("Failure!");
        });
    };

});

this doesnt work - data isnt even properly send to the server, instead of provided username and password all I see are nulls ( and I get 401 all the time ). URL's are the same. Can someone help me solve this?

I also tried sending bare string instead of 'data' object, it also didnt seem to work.

jQuery by default send data with Content-Type: x-www-form-urlencoded and AngularJS $http service send with Content-Type: application/json .

If you want to send data like jQuery then set the request header like this:

    var data = {
        username: username,
        password: password
    };

    $http.defaults.headers.post["Content-Type"] = "application/x-www-form-urlencoded";

    return $http.post(absUrl, data)
        .then(
            function(response){
                return "Successfully logged!";
            },
            function(response){
                window.alert("Failure!");
    });

Remember this is global configuration for $http service.

I don't know in which technology you are running your backend, but it's often better to use default AngularJS header application/json .

What is difference?

Data in application/x-www-form-urlencoded is send by uri for example: ?parm1=1&parm2=2&parm3=3

In .NET MVC WebAPI this will be binded for:

[HttpPost]
public HttpResponseMessage Simple(int parm1, int parm2, int parm3) {

}

Data in Content-Type: application/json is send by payload in JSON format for example: { parm1: 1, parm2: 2, parm3: 3 }

In .NET MVC WebAPI this will be binded for:

[HttpPost]
public HttpResponseMessage Simple(Parameters parameters) {

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM