0

I am using asp.net web api2 token based authentication. Works enough

 $("#Login").click(function () {
    var userName = $("#UserName").val();
    var password = $("#Password").val();

    $.ajax({
        url: "http://api.foo.net/token",
        type: "POST",
        crossDomain: true,
        data: {
            "username": userName,
            "password": password,
            "grant_type": "password"
        },
        dataType: "json",
        success: function (result) {
            alert("Logged in successfully");
            localStorage.setItem('Token', JSON.stringify(result));
        },
        error: function (xhr, status, error) {
            alert(status + " " + error);
        }
    });

});

but I want to convert AngularJS,i wrote a factory in app.js

.factory("API", function ($http) {
    var tokenLink = 'http://api.foo.net/token';

    return {
        getToken: function (username, password, success) {
            $http({
                url: tokenLink,
                method: 'POST',
                data: {
                    "username": username,
                    "password": password,
                    "grant_type": "password"
                },
                headers: {
                    'Accept': 'application/json, text/javascript, */*',
                    'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
                }
            }).success(function (data) {
                success(data);
            }).error(function (data, status, headers, config) {
                console.log("error");
            });
        }
    }
})

also controller.js

.controller('LoginCtrl', function ($scope, $http, API) {
    $scope.doLogin = function () {
        var loginData = {
            userName: $scope.loginData.username,
            password: $scope.loginData.password
        };
        API.getToken(loginData.userName,loginData.password,function(data){
            console.log(data);
            alert(data);
        });
    };
})

Well, while Jquery Ajax method works fine but this angular factory (API) not works. Throws "The response had HTTP status code 400."

However.Jquery $.ajax running but AngularJS $Http. not! Can someone help me?

  • Look on this question's answer (the one with bounty) http://stackoverflow.com/questions/24710503/how-do-i-post-urlencoded-form-data-with-http-in-angularjs - it looks just like the same issue. – Diana R Jan 12 '16 at 14:21
  • Hint to your code style, use `.success(success)`, do not wrap it in an anonymous function. – arve0 Jan 12 '16 at 14:22
  • Use your browser's debugger to look at URL, response and headers. Compare the two. Your code seems correct, probably a blunder somewhere. – arve0 Jan 12 '16 at 14:25
  • Why do you passing a callback function to a success handler instead of returning the httpPromise? Where does that example come from? – georgeawg Jan 12 '16 at 14:35

0 Answers0