StudentRik
StudentRik

Reputation: 1049

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?

Upvotes: 0

Views: 56

Answers (2)

Valery Kozlov
Valery Kozlov

Reputation: 1577

Your error related to cross-origin request - in other words you send request to another domain or specific route miss Access-Control-Allow-Origin server header.

Check ports, http/https and domain. Seems it's not related to your refactor.

Upvotes: 0

Ameer Hamza
Ameer Hamza

Reputation: 606

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);
    });
  }
})

Upvotes: 1

Related Questions