Programing

한 요청에 대한 HTTP 헤더 설정

lottogame 2020. 6. 5. 08:00
반응형

한 요청에 대한 HTTP 헤더 설정


앱에 기본 인증이 필요한 하나의 특정 요청이 있으므로 해당 요청에 대한 Authorization 헤더를 설정해야합니다. HTTP 요청 헤더 설정 에 대해 읽었 지만 알 수 있듯이 해당 메소드의 모든 요청에 ​​대해 해당 헤더를 설정합니다. 내 코드에는 다음과 같은 것이 있습니다.

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

그러나 모든 게시물 요청 이이 헤더를 보내는 것을 원하지 않습니다. 원하는 하나의 요청에 대해서만 헤더를 보내는 방법이 있습니까? 또는 요청 후 제거해야합니까?


구성 객체에는 $http호출 별 헤더에 전달하는 헤더 매개 변수가 있습니다.

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

}

참고 URL : https://stackoverflow.com/questions/11876777/set-http-header-for-one-request

반응형