2015-12-14 33 views
-1

我有一些问题。来自外部网址的AngularJS应用程序数据。这是我的代码。如何编写授权标题。响应HTTP状态401AngularJS HTTP头

app.controller('AddressController', function($scope, $http){ 
$http.defaults.headers.common.Authorization = 'username password'; 
$http.get('http://URL/resources/cities?sortBy=cityId&sortOrder=asc&offset=0&limit=100'). 
    success(function(data, status, headers, config){ 
     $scope.posts = data; 
    }). 
    error(function(data, status, headers, config){ 

    }); 
}); 
+0

您使用哪种外部服务?我的意思是像Apache一样。 – AndreaM16

+0

是啊阿帕奇服务器 –

+0

你把它整理出来了吗? – AndreaM16

回答

0

我已经在过去类似的问题,更确切地说,一个CORS问题。 你可以阅读更多关于跨域资源共享(CORS)

在几句话,CORS当你有没有发生设置访问Web服务上的特定文件或数据的权限,在您的情况下,请在您的Apache2服务上访问。 所以,当您尝试访问它们,它只是告诉你:“响应是HTTP状态401,访问被拒绝”

为了解决这个问题,换句话说,允许访问你的资源,你可以做两件事情:

  • 解决您的Apache2 config文件
  • 您AngularJS控制器

我总是去了第一个选项,固定我的Apache2设置的权限。配置文件。 您可以在Apache2文件夹的某些文件夹中找到您的Apache2.conf文件。 只需登录it's documentation即可。

现在我要告诉你我是如何解决这个问题的。简而言之,我的Apache2服务器上有一些Jsons,我需要将它们提取到我的AngularJS控制器上,以便在我的Views中显示一些数据。

我有这样的事情:

myController.js

myApp.controller("myController", ["$scope","$http",function($scope, $http){ 

    var controller = this; 

    $http.get('http://localhost/main.json').success(function(dataForViews){ 

     controller.data = dataForViews; 

    }) 
}]); 

在我HTML视图我只是请求的数据与语法,如:

<p> {{myController.dataForViews.Name}} </p> 

现在,为了允许访问,我把这段代码放在我的Apache2的.config

<VirtualHost *:80> 


    ServerAdmin [email protected] 

    #Giving permissions 
    Header set Access-Control-Allow-Origin "*" 

    ############################ Main Page ########################### 
    Alias /main.json /var/www/html/myApp/data/mainPages/mainJSON.json 

    #When localhost/myApp, you get the application that runs on localhost:9000 
    #with its jsons 
    <Location /myApp> 
     ProxyPass http://localhost:9000/ 
     ProxyPassReverse http://localhost:9000/ 
    </Location> 

    #Same thing for scripts, css, etc, like: 
    <Location /scripts> 
     ProxyPass http://localhost:9000/scripts/ 
     ProxyPassReverse http://localhost:9000/scripts/ 
    </Location> 

</VirtualHost> 

我能够允许访问我的资源卧像这样我的Apache2服务器上。 现在,你可以解决像我一样,或者,如果你得到一些错误,你可能需要看Apache2 Documentation

如果你要那么在AngularJS的方式解决它,看看:

我希望我已经帮助。