【问题标题】:Passing header parameters while loading Video in VideoJs在 VideoJs 中加载视频时传递标头参数
【发布时间】:2020-12-03 17:23:50
【问题描述】:

我正在尝试将视频加载到 React 项目中的 VideoJS 播放器中。视频是从一个 Web 服务返回的,该服务采用对用户进行身份验证的特定令牌。

假设视频是从以下 API 调用返回的:

localhost:8080/video/1/

要播放此视频,用户必须经过身份验证。换句话说,API 采用以下标头来返回成功的结果:

身份验证:令牌

我的 VideoJs 播放器内置在 React 组件中,如下所示:

import React from 'react'
import videojs from 'video.js'

export default class VideoComponent extends React.Component {

  componentDidMount () {
      this.videoJsOptions = {
        sources: [{
           src: 'http://localhost:8080/video/1/',
          type: 'video/mp4',
        }],
      }
      let player = videojs(this.videoNode, this.videoJsOptions, function onPlayerReady() {
        console.log('onPlayerReady', this)
      })

      this.player = player
  }
  render () {
      return (
            <div data-vjs-player>
              <video ref={node => this.videoNode = node} className="video-js"></video>
            </div>
      )       
  }
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

如何让我的视频组件获取调用 URL 的令牌并将请求标头传递给它?

【问题讨论】:

    标签: reactjs xmlhttprequest video.js request-headers


    【解决方案1】:

    如果用户被授权,我会将这个组件作为另一个组件的子组件,该组件的唯一职责是进行 API 调用并呈现 VideoComponent。类似的东西。

    如果用户未经授权,您可能希望向用户提供某种类型的重定向或错误消息反馈。我没有在我的代码 sn-p 中加入它。

    export default class VideoAuth extends React.Component {
        state = {
            isAuthorized: false
        }
    
        async componentDidMount() {
            const authRequest = await someAuthRequest()
            if (authRequest.ok) {// or however the data structure looks like
                this.setState({ isAuthenticated: true })
            }
        }
    
        render() {
            return this.state.isAuthenticated ? <VideoComponent /> : <div> Authorizing... </div>
        }
    }
    

    【讨论】:

    • 这将如何解决我的问题?我需要在检索视频的 api 标头中传递令牌。换句话说,localhost:8080/video/1 需要在请求标头中有一个令牌。否则视频不会加载到播放器中,因为请求返回 401 未授权
    • @HodaBaydoun 这个令牌在你的应用程序中的什么位置?
    • 是的,我在 localStorage 中有它,但是它没有被添加到请求标头中
    • 那我就糊涂了。我是说将您需要的任何凭据传递到此行const authRequest = await someAuthRequest()。如果调用成功,则使用视频播放器安装组件。在您的请求完成之前,有一个三元组可以阻止 VideoComponent 过早安装。您的视频播放器还需要哪些其他信息才能播放?如果它需要请求中的信息,那么做同样的事情,除了将三元包裹在 &lt;video&gt; 周围而不是制作一个新组件
    猜你喜欢
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2021-09-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多