为一个请求设置HTTP标头

dnc*_*253 157 javascript http-headers angularjs

我的应用程序中有一个特殊请求需要基本身份验证,因此我需要为该请求设置Authorization标头.我读到了有关设置HTTP请求标头的内容,但据我所知,它将为该方法的所有请求设置该标头.我的代码中有类似的东西:

$http.defaults.headers.post.Authorization = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==";
Run Code Online (Sandbox Code Playgroud)

但我不希望我的每个帖子请求发送此标头.有没有办法只为我想要的一个请求发送标题?或者我是否必须在我的要求后将其删除?

Yun*_*chi 315

$http为每个调用标头传递的配置对象中有一个headers参数:

$http({method: 'GET', url: 'www.google.com/someapi', headers: {
    'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Run Code Online (Sandbox Code Playgroud)

或者使用快捷方式:

$http.get('www.google.com/someapi', {
    headers: {'Authorization': 'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ=='}
});
Run Code Online (Sandbox Code Playgroud)

$ http服务文档中提供了有效参数列表.

  • 对我不起作用.我以这种方式添加的标头都没有添加到实际请求中. (30认同)
  • @ dnc253这也适用于快捷方法.代码为`$ http.get('www.google.com/someapi', {headers:{'Authorization':'Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ =='}}); (17认同)
  • 每当我尝试设置标题时,我的请求都会以"OPTION"请求的形式出现,因此我的端点返回一个"404 NOT FOUND",这是有道理的:它只知道`GET/someResource`而不是'OPTIONS/someResource` (4认同)

小智 19

试试这个,也许它有效;)

.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');
})
Run Code Online (Sandbox Code Playgroud)

并确保你的后端也工作,试试这个.我正在使用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');
    }

}
Run Code Online (Sandbox Code Playgroud)