我的应用程序中有一个需要基本身份验证的特定请求,因此我需要为该请求设置Authorization标头。我读过有关设置HTTP请求标头的信息,但是据我所知,它将为该方法的所有请求设置标头。我的代码中有这样的内容:
$http.defaults.headers.post.Authorization = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==";
但是我不希望我的每一个帖子请求都发送此标头。有什么方法可以仅为我想要的一个请求发送标头吗?还是在请求后必须将其删除?
传递给$http
每次调用标头的config对象中有一个标头参数:
$http({method: 'GET', url: 'www.google.com/someapi', headers: {
'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
或使用快捷方式:
$http.get('www.google.com/someapi', {
headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
有效参数的列表可在$ http服务文档中找到。
试试这个,也许行得通;)
.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');
})
并确保您的后端也可以使用,请尝试此操作。我正在使用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');
}
}
本文地址:http://javascript.askforanswer.com/weiyigeqingqiushezhihttpbiaotou.html
文章标签:angularjs , http-headers , javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
文章标签:angularjs , http-headers , javascript
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!
评论已关闭!