简体   繁体   English

AngularJS在$ http.get中添加标题

[英]AngularJS Adding a header to the $http.get

I'm trying to add the 'Authorization' header containing a token for future HTTP request. 我正在尝试添加“授权”标头,其中包含用于将来的HTTP请求的令牌。 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); 

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. 函数getToken()返回一个值,但是由于我是该主题的新手,所以我不确定将令牌添加到标头的方式是否正确。 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. 我还尝试将其添加到诸如$ http.get(URL,httpHeaders)之类的get请求中,但是它也没有起作用。

I'm not sure I understand your problem completely as you did not provide what you call 我不确定您是否完全了解您的问题,因为您没有提供您所说的内容

httpConfig httpConfig

If you're struggling to declare the headers, try making the get request like this: 如果您在声明标头方面很费力,请尝试发出以下get请求:

$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. 您可以在其中的标题对象中添加任何您喜欢的标题。

Try adding this in your config block and set the token in your rootscope 尝试将其添加到配置块中,并在rootscope中设置令牌

$httpProvider.interceptors.push({
    request: function (config) {
        config.headers.Authorization = $rootScope.token;
        return config;
    }
})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM