StudentRik StudentRik - 3 months ago 9
AngularJS Question

Angular $http.post to retrieve JWT

I am attempting to make my code more reusable, but have come across a problem when making

$http
calls, if I use my normal way:

vm.loginUser = function () {
var userData = {
username: vm.userName,
password: vm.userPassword,
grant_type: "password",
client_id: "E0..."
};
console.log('userData: ', userData);
var config = {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
transformRequest: function (data) {
var str = [];
for (var d in data)
if (data.hasOwnProperty(d)) str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
};
console.log('config: ', config);
$http.post('https://a.n.org.uk/token', userData, config)
.then(function (response) {
console.log('Button clicked: ', response);
}, function (response) {
console.log(response.data.error_description);
}, function (response) {
console.log(response.data);
});


This works fine and doesn't give me any problems. I have made a
factory
that is basically the same but doesn't seem to work with giving me
OPTIONS
error in the console and
preflight check... No 'Access-Control-Allow-Origin' header'
I wondered if this is a simple fix, I am using Web API.

factory("homeResource", function ($http, $q) {
return {
getUser: getUser
};

function getUser(userData) {
var request = $http({
method: "post",
url: "https://a.n.org.uk/token",
data: userData,
config: {
headers: {"Content-Type": "application/x-www-form-urlencoded"},
transformRequest: function (data) {
var str = [];
for (var d in data)
if (data.hasOwnProperty(d)) str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
return str.join("&");
}
}
});

return (request.then(handleSuccess, handleError));
}

function handleSuccess(response) {
return ( response.data );
}


In my
Ctrl page
I pass in my
homeResource
and call it like so
homeResource.getUser(userData).then(function (res) {console.log(res);});
and get the errors mentioned. Is there a way to make this work?

Answer

try the following factory method

   app.factory('homeResource', function($http) {
       return {
           getUser: function(userData) {
             var config = {
               headers: {"Content-Type": "application/x-www-form-urlencoded"},
               transformRequest: function (data) {
                   var str = [];
                   for (var d in data)
                        if (data.hasOwnProperty(d))
                           str.push(encodeURIComponent(d) + "=" + encodeURIComponent(data[d]));
                   return str.join("&");
              }
            };
            return $http.post('https://a.n.org.uk/token', userData, config);
           }
       }
    });

and use it in your controller like this.

app.controller('AppCtrl',function($scope, homeResource){ 
  vm.loginUser = function () {
      var userData = {
      username: vm.userName,
      password: vm.userPassword,
      grant_type: "password",
      client_id: "E0..."
      };
    homeResource.getUser(userData).success(function(res){
       console.log("response is",res);
    })
    .error(function(err) {
       console.log("err is",err);
    });
  }
})