Javascript 为一个请求设置 HTTP 标头
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11876777/
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
Set HTTP header for one request
提问by dnc253
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:
我的应用程序中有一个需要基本身份验证的特定请求,因此我需要为该请求设置 Authorization 标头。我阅读了有关设置 HTTP 请求标头的信息,但据我所知,它将为该方法的所有请求设置该标头。我的代码中有这样的东西:
$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?
但我不希望我的每个帖子请求都发送这个标头。有什么办法可以只为我想要的一个请求发送标头吗?还是我必须在我提出要求后将其删除?
回答by Yunchi
There's a headers parameter in the config object you pass to $http
for per-call headers:
您传递给$http
每个调用标头的配置对象中有一个标头参数:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Or with the shortcut method:
或者使用快捷方法:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
The list of the valid parameters is available in the $httpservice documentation.
$http服务文档中提供了有效参数的列表。
回答by donny
Try this, perhaps it works ;)
试试这个,也许它有效;)
.factory('authInterceptor', function($location, $q, $window) {
return {
request: function(config) {
config.headers = config.headers || {};
config.headers.Authorization = 'xxxx-xxxx';
return config;
}
};
})
.config(function($httpProvider) {
$httpProvider.interceptors.push('authInterceptor');
})
And make sure your back end works too, try this. I'm using RESTful CodeIgniter.
并确保您的后端也能正常工作,试试这个。我正在使用 RESTful CodeIgniter。
class App extends REST_Controller {
var $authorization = null;
public function __construct()
{
parent::__construct();
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
if ( "OPTIONS" === $_SERVER['REQUEST_METHOD'] ) {
die();
}
if(!$this->input->get_request_header('Authorization')){
$this->response(null, 400);
}
$this->authorization = $this->input->get_request_header('Authorization');
}
}