Angular的新手 - 无法想象这一个。设置Authorization标头时,$ http调用无法到达服务器。我的功能:
loginHttp: function(name, pw) {
var req = {
method: 'GET',
url: 'http://mywebsite/login',
headers: {
'Authorization': "Basic "+ this.b64EncodeUnicode("user1:pass1")
},
data: { test: 'test' }
}
//$http.defaults.headers.common['Authorization'] = "Basic "+ this.b64EncodeUnicode("user1:pass1");
//$http.defaults.headers.common['Accept'] = "text/html";
$http(req).then(function(resp) {
console.log('Success', resp);
// For JSON responses, resp.data contains the result
}, function(err) {
console.error('ERR', err);
// err.status will contain the status code
} )
},
回应是:
ERR Object {data:null,status:0,headers:headersGetter /<(),config:Object,statusText:“”}
没有标题工作正常或设置另一个标题,例如接受:...
非常感谢任何帮助。
我的完整LoginService服务在这里:
.service('LoginService', function($q, $http) {
return {
loginHttp: function(name, pw) {
alert(this.b64EncodeUnicode("teacherb:loops411"))
var req = {
method: 'GET',
url: 'http://mywebsite/login',
headers: {
'Authorization': "Basic "+ this.b64EncodeUnicode("teacherb:loops411")
},
data: { test: 'test' }
}
//$http.defaults.headers.common['Authorization'] = "Basic "+ this.b64EncodeUnicode("teacherb:loops411");
//$http.defaults.headers.common['Accept'] = "text/html";
$http(req).then(function(resp) {
console.log('Success', resp);
// For JSON responses, resp.data contains the result
}, function(err) {
console.error('ERR', err);
// err.status will contain the status code
} )
},
b64EncodeUnicode: function (str) {
return btoa(encodeURIComponent(str).replace(/%([0-9A-F]{2})/g, function(match, p1) {
return String.fromCharCode('0x' + p1);
}));
},
loginUser: function(name, pw) {
var deferred = $q.defer();
var promise = deferred.promise;
if (name == 'user' && pw == 'secret') {
deferred.resolve('Welcome ' + name + '!');
} else {
deferred.reject('Wrong credentials.');
}
promise.success = function(fn) {
promise.then(fn);
return promise;
}
promise.error = function(fn) {
promise.then(null, fn);
return promise;
}
return promise;
}
}
})
答案 0 :(得分:0)
看起来它是一个HTTP访问控制(CORS)问题 - 在访问跨源URL时无法使用auth标头。