所有请求的 AngularJS $http 自定义标头
问题描述:
我想知道是否有任何方法可以通过添加自定义信息来配置所有 $http 请求标头.类似于配置的东西:
I was wondering if there is any way to configure all $http requests header with adding custom info. Something like config :
var config = {headers: {
'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==',
'Accept': 'application/json;odata=verbose'
}
};
但是对于所有 $http 调用,我将在不同的服务中进行.我确定有一个解决方案 :D.Thanks
But for all $http calls I will make in different services. I'm sure there is a solution :D.Thanks
答
您可以创建一个 $http
拦截器来扩展您的标头:
You can create a $http
interceptor to extend your header:
myapp.factory('httpRequestInterceptor', function () {
return {
request: function (config) {
config.headers['Authorization'] = 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==';
config.headers['Accept'] = 'application/json;odata=verbose';
return config;
}
};
});
myapp.config(function ($httpProvider) {
$httpProvider.interceptors.push('httpRequestInterceptor');
});