AngularJS在$ http.get中添加标题 [英] AngularJS Adding a header to the $http.get
问题描述
我正在尝试添加授权"标头,其中包含用于将来的HTTP请求的令牌.检索令牌似乎很好,但是在发出get请求时,它会失败,并显示一条未经授权的错误消息.在检查请求标头之后,请求标头在请求块中不存在...
I'm trying to add the 'Authorization' header containing a token for future HTTP request. Retrieval of the token seems to be fine however when making a get request it fails with an Unauthorized error message. After checking the request headers Authorization header does not exist in the request block...
window.crUtil = /*window.crUtil ||*/ (function() {
// Angular Services
var $injector = angular.injector(['ng']);
var $http = $injector.get('$http');
// getting the CFF data
function get_data() {
getJWTAWS();
var url = '/AWS/getDATA/555';
console.log('AUTH header before call: ' + $http.defaults.headers.common.Authorization);
$http.get(url,httpHeader).then(function successCallback(response) {
var data = response.data;
var cff = initCff();
alert(data.itemId);
}, function errorCallback(response) {
initCff();
alert("Error while getting data ");
});
}
function getJWTAWS() {
var httpConfig = {
cache: true,
params: {}
};
$http.get('/AWS/token', httpConfig).then(
function(response) {
if (response.data.accessToken) {
// add jwt token to auth header for all requests made by the $http service
$http.defaults.headers.common.Authorization = response.data.tokenType + ' ' + response.data.accessToken;
}
},
function(error) {
alert('jwt token could not be retrieved.');
}
);
}
})();
var result = util.get_data();
console.log ('called search function ' + result);
函数getToken()返回一个值,但是由于我是该主题的新手,所以我不确定将令牌添加到标头的方式是否正确. 您能否建议在请求中包含标头的正确方法.我也试图将其添加到get请求中,例如 $ http.get(URL,httpHeaders)... 但它也不起作用.
Function getToken() returns a value but as I'm new on that topic I'm not quite sure if the way I added the token to the headers is proper. Could you please advise on the proper way to include the headers in the request. I also tried to add it to the get request like $http.get(URL,httpHeaders)... but it also didn't work.
推荐答案
我不确定您是否完全了解您的问题,因为您没有提供您所称的内容
I'm not sure I understand your problem completely as you did not provide what you call
httpConfig
httpConfig
如果您在声明标头方面很费力,请尝试发出以下get请求:
If you're struggling to declare the headers, try making the get request like this:
$http({
method: 'GET',
url: YOUR_URL,
headers: {
'Content-Type': 'application/json',
'Authorization': AUTH_STRING_HERE
}
}).then(function (response) { ... });
您可以在其中的标题对象中添加任何您喜欢的标题.
You can add any headers you like in the headers object there.
这篇关于AngularJS在$ http.get中添加标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!