我的AngularJS驱动的前端应该使用Basic Auth。我尝试了不同的方法,但没有任何作用 - 请求是在没有Authorization
标题的情况下发送的:
$http
服务对象配置 码
(function() {
var app = angular.module('portfolio', []);
app.controller('ProjectsListController', ['$http', function($http) {
var projectsList = this;
projectsList.projectsListData = [];
$http.defaults.headers.common.Authorization = 'Basic dXNlcjpwd2Q=';
$http.get(config['api_server_url'] + '/projects').success(function(data) {
projectsList.projectsListData = data;
});
}]);
})();
请求标题
OPTIONS /projects HTTP/1.1
Host: foo.bar.tld
Connection: keep-alive
Access-Control-Request-Method: GET
Origin: http://baz.buz.loc
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://baz.buz.loc/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2
码
(function() {
var app = angular.module('portfolio', []);
app.controller('ProjectsListController', ['$http', function($http) {
var projectsList = this;
projectsList.projectsListData = [];
$http.get(config['api_server_url'] + '/projects', {
headers: {'Authorization': 'Basic dXNlcjpwd2Q='}
}).success(function(data) {
projectsList.projectsListData = data;
});
}]);
})();
请求标题
OPTIONS /projects HTTP/1.1
Host: foo.bar.tld
Connection: keep-alive
Cache-Control: max-age=0
Access-Control-Request-Method: GET
Origin: http://baz.buz.loc
User-Agent: Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
Access-Control-Request-Headers: accept, authorization
Accept: */*
Referer: http://baz.buz.loc/
Accept-Encoding: gzip, deflate, sdch
Accept-Language: de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2
app
config 码
(function() {
var app = angular.module('portfolio', []);
app.run(['$http', function($http) {
$http.defaults.headers.common['Authorization'] = 'Basic dXNlcjpwd2Q=';
}]);
app.controller('ProjectsListController', ['$http', function($http) {
var projectsList = this;
projectsList.projectsListData = [];
$http.get(config['api_server_url'] + '/projects').success(function(data) {
projectsList.projectsListData = data;
});
}]);
})();
请求标题
Accept:*/*
Accept-Encoding:gzip, deflate, sdch
Accept-Language:de-DE,de;q=0.8,en-US;q=0.6,en;q=0.4,ru;q=0.2
Access-Control-Request-Headers:accept, authorization
Access-Control-Request-Method:GET
Connection:keep-alive
Host:foo.bar.tld
Origin:http://baz.buz.loc
Referer:http://baz.buz.loc/
User-Agent:Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36
因此,缺少Authorization: Basic dXNlcjpwd2Q=
标头。这里有什么问题以及如何让它发挥作用?
答案 0 :(得分:0)
与this问题一样,您需要设置$http
服务的配置,而不是在控制器中,但在run
或config
块中
app.run(['$http', function($http) {
$http.defaults.headers.common['Authorization'] = /* ... */;
}]);