Is there a way to include a custom http header in

2019-03-28 06:11发布

问题:

I have a simple html5 player, implemented with videoJS. In order to properly retrieve the source files from the server, I need to set a custom header in the request for the video.

Since the application uses AngularJS, I implemented an Interceptor to set the header:

myApp.factory('headerInterceptor', function () {
  return {
    request: function (config) {
        config.headers['my-header'] = 'test';
        return config;
    }
  };
});

myApp.config(['$httpProvider', function($httpProvider) {
    $httpProvider.interceptors.push('headerInterceptor');
}

Problem with this, is that the call to the video is not catched by it, so no header is set (it is though for other resources). So angular does not load the videos. No big surprise in that. Checking the Network tab in developer tools, found out that videoJS initiates the call:

But finding my way in the videoJS plugin has been difficult, and couln't find where the calls are made. Im just wondering, is there a simple way to set the header for this call? doesn't matter if it's plain javascript, or through angular, or even modifying videoJS plugin.

回答1:

Inside an Angular run block, you can override the videojs plugin XHR beforeRequest function. YMMV, but if you use HLS plugin for example, you could do something like that:

angular.module('app', []).run(function($localStorage) {

    var _beforeRequest = videojs.Hls.xhr.beforeRequest;
    videojs.Hls.xhr.beforeRequest = function(options) {
        if (_.isFunction(_beforeRequest)) {
            options = _beforeRequest(options);
        }
        if ($localStorage.token) {
            options.headers = options.headers || {};
            options.headers.Authorization = 'Token ' + $localStorage.token;
        }
        return options;
    };
});


回答2:

I had ran into this issue as well. I wanted to send an authorization header along with every video and image requested to my site and use the native html5 video tag. After searching for a long time, I was not able to find any solution that would allow custom headers. In the end, I decided to create a cookie at the start of the application. Since cookies are sent on every request, I was able to setup my Web API to look for this cookie only when images and videos are requested. That way the rest of the site would continue to use the authorization header.

ngCookies had to be added to the application:

var app = angular.module('myApp', ['ngCookies']);

Then at the start of the application:

app.run(['$cookies', function ($cookies) {
      $cookies.put("[COOKIE_NAME]", "[TOKEN]");
}