首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >为一个请求设置HTTP标头

为一个请求设置HTTP标头
EN

Stack Overflow用户
提问于 2012-08-09 12:22:13
回答 2查看 302.9K关注 0票数 159

我的应用程序中有一个特定的请求需要基本身份验证,因此我需要为该请求设置Authorization头。我读到过关于setting HTTP request headers的文章,但据我所知,它将为该方法的所有请求设置标头。我的代码中有类似这样的内容:

$http.defaults.headers.post.Authorization = "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==";

但是我不希望我的每个post请求都发送这个头文件。有没有办法只为我想要的一个请求发送报头?或者我必须在请求后将其删除?

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-08-09 12:39:01

在您传递给$http的配置对象中有一个headers参数,用于每次调用的headers:

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

或使用快捷方式:

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

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

票数 322
EN

Stack Overflow用户

发布于 2014-11-27 12:59:32

试试这个,也许能行得通;)

.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');
    }

}
票数 20
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11876777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档