将自定义标头添加到videojs播放器源
问题描述:
我有一个用于处理流式视频m3u8文件的后端api(使用express).
I have a backend api (using express) that handles a streaming video m3u8 file.
http://localhost:3000/api/stream.m3u8
此终结点仅适用于正确的用户token
.
This endpoint will only work with a proper user token
.
路由器
router.get('/api/stream.m3u8', controller.stream);
控制器
exports.stream = function(req, res) {
var token = ''; // ? not sure how to get access to a sent up token
if (!token) res.status(401).json('Not authorized');
// if token is valid, proceed
};
在前端,我正在使用videojs.
On the front end, I am using videojs.
var player = videojs('my-player', {})
// set source to my backend api m3u8 file
player.src({
src: 'http://localhost:3000/api/stream.m3u8',
type: 'application/x-mpegURL'
});
是否可以在videojs插件中添加自定义标头,以将数据发送到我的后端?
Is there a way to add a custom header to the videojs plugin to send up data to my backend?
答
我使用的解决方案是拦截浏览器XHR请求(使用xhook npm包)并以编程方式设置标头.贝娄是一个简单的例子:
The solution I've gone with was to intercept browser XHR requests(using the xhook npm package) and set headers programmatically. Bellow is a simple example:
...
this.player.src({
src: SOME_VIDEO_URL,
});
...
/**
* add manifest authorization header
*/
window.xhook.before((request, callback) => {
// only set header request for the videojs src url (don't touch other xhr requests)
if (request.url === SOME_VIDEO_URL) {
request.xhr.setRequestHeader('Authorization', manifestAuthorization);
}
callback();
});