Angular $ http.post来检索JWT

时间:2016-09-08 11:55:15

标签: angularjs

我正在尝试使我的代码更具可重用性,但在进行$http调用时遇到问题,如果我使用我的正常方式:

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

这很好,并没有给我任何问题。我创建的factory基本相同,但似乎无法在控制台中发出OPTIONS错误preflight check... No 'Access-Control-Allow-Origin' header'我想知道这是否是一个简单的修复,我是使用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 );
  }

在我的Ctrl page中,我传递了homeResource并将其称为homeResource.getUser(userData).then(function (res) {console.log(res);});,并获得提及的错误。有没有办法使这项工作?

2 个答案:

答案 0 :(得分:1)

尝试以下工厂方法

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

并在你的控制器中使用它。

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

答案 1 :(得分:0)

您的错误与跨源请求有关 - 换句话说,您发送请求到另一个域或特定路由未命中Access-Control-Allow-Origin服务器标头。

检查端口,http / https和域。似乎它与你的重构无关。