6

是否可以仅为指定域设置标头?

执行此操作的“正常”方式会为所有调用添加该标头,甚至包括检索 HTML 模板的调用。

$http.defaults.headers.common['Authorization']='...';

到目前为止,除了使用 $http 拦截器之外,我看不到任何其他方式,但如果你能想到一个,我很好奇。

谢谢。

4

1 回答 1

8

创建拦截器是我处理这个问题的方式。我不确定另一种方式,所以,无论如何,这里有一个例子。:)

您可以创建一个注册的拦截器$httpProvider。Angular 将传递默认配置对象进行修改,您可以在那里修改标题。

下面是一个基于Angular $http 文档页面的快速示例:

//register interceptor as a service
$provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
    return {
        // optional method
        'request': function(config) {
            //Figure out which headers you want and set them just for this request.
            config.headers = {"myHeader":"Special"}

            return config;
        }
    };
});

$httpProvider.interceptors.push('myHttpInterceptor');
于 2014-03-18T21:35:01.967 回答