簡體   English   中英

為一個請求設置HTTP標頭

[英]Set HTTP header for one request

我的應用程序中有一個特殊請求需要基本身份驗證,因此我需要為該請求設置Authorization標頭。 我讀到了有關設置HTTP請求標頭的內容 ,但據我所知,它將為該方法的所有請求設置該標頭。 我的代碼中有類似的東西:

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

但我不希望我的每個帖子請求發送此標頭。 有沒有辦法只為我想要的一個請求發送標題? 或者我是否必須在我的要求后將其刪除?

在每個調用標頭傳遞給$http的配置對象中有一個headers參數:

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM