首页 > 解决方案 > 使用 node.js 将视频从 AWS 流式传输到网页并做出反应

问题描述

我正在尝试使用 react.js 作为客户端和 node.js 作为服务器将我的 AWS S3 存储桶中的 mp4 视频流式传输到网页上。然而,我对这两个都很陌生。在前端,在我的一个反应组件中,我在渲染中有以下内容(为了相关性,省略了返回中的一些代码):

render() {
  const { classes } = this.props;
  return(
    <video id = "video" width = "1280" height = "720" controls>
    Your browser does not support the video tag.
      <source src={this.state.videoNow} type='video/mp4' />
    </video> 
  );
}

在同一个类中,我有一个 componentDidMount() 函数:

componentDidMount() {
   fetch("/api/annotate", {
     headers: {'Authorization': 'Bearer ' + localStorage.getItem('token')}
   })
     .then(res => {
       this.setState({
         videoNow: res
        });
      ,(error) => {
          console.log(error)
      })
}

在我的 server.js 文件中,我有以下内容:

app.get('/api/annotate',
  (req, res) => {
    var s3 = new AWS.S3();
    const mimetype = 'video/mp4';
    const file = '<video source in bucket>';
    const cache = 0;
    console.log('const mimetype, file, and cache declared');
    s3.listObjectsV2({Bucket: <name of bucket>, MaxKeys: 1, Prefix: file}, function(err, data) {
      if (err) {
        return res.sendStatus(404);
      }
      console.log('made request to s3 to list objects');

      if ((req != null) && (req.headers.range != null)) {
        var range = req.headers.range;
        var bytes = range.replace(/bytes=/, '').split('-');
        var start = parseInt(bytes[0], 10);
        var total = data.Contents[0].Size;
        var end = bytes[1] ? parseInt(bytes[1], 10) : total - 1;
        var chunksize = (end - start) + 1;
        console.log('declared range, bytes, start, total, end, chunksize vars');

        res.writeHead(206, {
           'Content-Range'  : 'bytes ' + start + '-' + end + '/' + total,
           'Accept-Ranges'  : 'bytes',
           'Content-Length' : chunksize,
           'Last-Modified'  : data.Contents[0].LastModified,
           'Content-Type'   : mimetype
        });
        console.log('wrote header');
        s3.getObject({Bucket: <name of bucket>, Key: file, Range: range}).createReadStream().pipe(res);
        console.log('got object from s3 and created readstream');
      }
      else
      {
        res.writeHead(200,
        {
            'Cache-Control' : 'max-age=' + cache + ', private',
            'Content-Length': data.Contents[0].Size,
            'Last-Modified' : data.Contents[0].LastModified,
            'Content-Type'  : mimetype
        });
        s3.getObject({Bucket: <name of bucket>, Key: file}).createReadStream().pipe(res);
        console.log('fell into else statement, wrote header');
      }


    });
  });

当我运行这段代码时,我注意到我的 server.js 文件中的 else 语句总是运行一次,然后什么也没有发生。视频无法加载,并且控制台指出找不到视频。如果我将我的反应组件中的视频源更改为 src='/api/annotate' 视频加载完美。问题是我正在尝试添加身份验证,这仅在我有 componentDidMount 时才有效。我一直在寻找有关如何解决此问题的几天,但找不到太多。再一次,我对这一切都很陌生。任何建议将不胜感激!!!

标签: node.jsreactjsamazon-web-servicesamazon-s3video-streaming

解决方案


在我看来,您正在尝试在源中设置实际的视频数据。这种方式不太可能奏效。另外,我不确定您为什么通过 node.js 服务器从 S3 提供文件。

如果您的 node.js 简单地生成一个预签名的 URL并返回它,这似乎是一个更好的解决方案,然后可以轻松地将其设置为源。他们也不必通过您的笔记应用程序传输所有数据。

更好的做法是将 Cloudfront 放在您的 S3 存储桶前面,然后使用相同的生成预签名 URL


推荐阅读