javascript 从 ngInit 在 AngularJS 中全局设置自定义 HTTP 标头

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20102605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 17:43:06  来源:igfitidea点击:

Globally set custom HTTP header in AngularJS from ngInit

javascripthttprestangularjsbasic-authentication

提问by PhoenixS

I am unable to set custom HTTP header taken from ngInitin AngularJS.

我无法设置从ngInitAngularJS 中获取的自定义 HTTP 标头。

I set variable using ngInit in html:

我在 html 中使用 ngInit 设置变量:

<div ng-init="myApiKey='valueOfVar'"></div>

Now I want to use this variable in all HTTP requests. I tried to set it in app.config and in controller too.

现在我想在所有 HTTP 请求中使用这个变量。我也尝试在 app.config 和控制器中设置它。

  • If I set it immediately, variable is undefined.

  • If I set it in $scope.$watchcallback function, variable is defined, but HTTP requests are without that header.

  • 如果我立即设置它,变量是未定义的。

  • 如果我在$scope.$watch回调函数中设置它,则定义了变量,但 HTTP 请求没有该标头。

I set header with:

我设置标题:

$http.defaults.headers.common.Authorization = 'something';

(or via $httpProvider, when in app.config) and then use it in service utilizing $resource. My code looks like [this][1]

(或通过$httpProvider,当在 app.config 中时),然后在服务中使用$resource. 我的代码看起来像 [this][1]

I tried to set it in config, in run, in controller and as a service, but nothing worked for me yet. Thank you in advance for any advice given.

我试图将它设置在config, in , in run, in controller 和作为服务,但对我来说还没有任何效果。预先感谢您提供的任何建议。

Edit:Now I have interceptor:

编辑:现在我有拦截器:

myApp.config(function ($httpProvider) {
    $httpProvider.interceptors.push('httpRequestInterceptor');
});

myApp.factory('httpRequestInterceptor', ['$rootScope', function($rootScope) {
    return {
        request: function($config) {
            $config.headers['Authorization'] = 'Basic ' + $rootScope.apiKey;
            return $config;
        }
    };
}]);

But $rootscope.apiKey(which is set in main controller) is undefinedat first call. After that, it's okay (and set).

但是$rootscope.apiKey(在主控制器中设置)是undefined第一次调用。之后,就可以了(并设置)。

回答by Karim Oukara

the following code will allow you to intercept all http requestes of your application and to add a property 'language' in the header of the request

以下代码将允许您拦截应用程序的所有 http 请求,并在请求的标头中添加属性“语言”

angular.module('app', ['ngRoute', 'ngResource']).run(function($http) {
  $http.defaults.headers.common.language='fr-FR';
});

we can add many properties in the http header

我们可以在 http 标头中添加许多属性

回答by Fals

If you wanna modify request/response in AngularJS you should do a deeply read about Interceptor:

如果你想在 AngularJS 中修改请求/响应,你应该深入阅读Interceptor

  • Angular JS Web Site: $http
  • Angular JS 网站:$http

You can call $http(config), where config is a object with every configuration. There's a configuration there for headers, where you should put your code:

您可以调用 $http(config),其中 config 是每个配置的对象。那里有一个配置headers,你应该把你的代码放在那里:

headers – {Object} – Map of strings or functions which return strings representing HTTP headers to send to the server. If the return value of a function is null, the header will not be sent.

headers – {Object} – 返回表示要发送到服务器的 HTTP 标头的字符串的字符串或函数的映射。如果函数的返回值为空,则不会发送标头。

If you google about Interceptor, you will get a full list of blogs explaining how to use It, and providing example codes, here's one that help me out sometime ago:

如果你在谷歌上搜索 Interceptor,你会得到一个完整的博客列表,解释如何使用它,并提供示例代码,这是前一段时间帮助我的一个:

Understanding angular $http interceptors

了解有角度的 $http 拦截器

回答by PhoenixS

OK, so for anybody trying to do the same - Interceptorswere the key (thank you Falsa lot), but problem was with the $rootScope. As I wrote in question, when Interceptor was called the first time, $rootScope.apiKeywasn't set yet (on consecutive requests, it was already set).

好的,所以对于任何试图做同样事情的人 -拦截器是关键(非常感谢Fals),但问题出在$rootScope. 正如我所写的那样,当第一次调用 Interceptor 时,$rootScope.apiKey还没有设置(在连续请求中,它已经设置了)。

Right way (or The working way) was to pass variable to AngularJS not through ngInit, but through $window. So I added to my HTML code:

正确的方法(或工作方法)是将变量传递给 AngularJS ngInit,而不是通过,而是通过$window。所以我添加到我的 HTML 代码中:

<script>window.apiKey = 'myValue';</script>

and then pass it to Interceptor exactly the same way as $rootScope- You can literally just replace all occurences of $rootScopein edit of my question with $windowand now it's working - even for the first request!

然后以完全相同的方式将其传递给拦截器$rootScope- 您实际上可以将$rootScope我的问题编辑中的所有出现替换为$window现在它正在工作 - 即使是第一个请求!

Thank you Fals once again.

再次感谢法尔斯。