为一个请求设置 HTTP 标头
我的应用中有一个需要基本身份验证的特定请求,因此我需要为该请求设置 Authorization 标头.我阅读了 设置 HTTP 请求标头,但据我所知,它会设置该方法的所有请求的标头.我的代码中有这样的东西:
I have one particular request in my app that requires Basic authentication, so I need to set the Authorization header for that request. I read about setting HTTP request headers, but from what I can tell, it will set that header for all requests of that method. I have something like this in my code:
$http.defaults.headers.post.Authorization = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==";
但我不希望我的每个帖子请求都发送此标头.有什么办法可以只为我想要的一个请求发送标头吗?还是必须在我提出要求后将其删除?
But I don't want every one of my post requests sending this header. Is there any way to send the header just for the one request I want? Or do I have to remove it after my request?
您传递给 $http
的配置对象中有一个 headers 参数,用于每个调用的标头:
There's a headers parameter in the config object you pass to $http
for per-call headers:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
或者使用快捷方式:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
有效参数列表在 $http 服务中可用文档.
The list of the valid parameters is available in the $http service documentation.