node.js - 使用 Node.js 和 React 将视频从 AWS 流式传输到网页上

标签 node.js reactjs amazon-web-services amazon-s3 video-streaming

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

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 语句始终运行一次,然后什么也没有发生。视频无法加载,控制台指出找不到视频。如果我将 React 组件中的视频源更改为 src='/api/annotate' ,视频将完美加载。问题是我正在尝试添加身份验证,并且只有当我有一个 componentDidMount 时这才有效。我已经搜索了好几天如何解决这个问题,但找不到太多。再说一次,我对这一切都很陌生。任何建议将非常感激!!!

最佳答案

在我看来,您正在尝试在源中设置实际的视频数据。但这种情况不太可能发生。另外,我不确定为什么您要通过 Node.js 服务器从 S3 提供文件。

如果你的node.js只是g enerated a pre-signed URL,这似乎是一个更好的解决方案并返回该值,然后可以轻松地将其设置为源。他们的方式所有数据也不必通过您的笔记应用程序传输。

更好的方法是将 Cloudfront 放在 S3 存储桶前面,然后使用相同的 generating presigned URL's for that .

关于node.js - 使用 Node.js 和 React 将视频从 AWS 流式传输到网页上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51529464/

相关文章:

javascript - 如何将 ids 列表传递给 mysql 从 NodeJs 删除查询

reactjs - React Js需要 'fs'

amazon-web-services - AWS Glue Crawler 因 S3 上的 1100 万个文件而失败

amazon-web-services - Terraform RDS 和证书颁发机构

amazon-web-services - 无法为 AWS es 域注册快照存储库

javascript - 从 Observable.create 返回的函数如何/何时执行(rxjs)

javascript - Node.js - 在继续之前从 MySQL 获取返回值

reactjs - 使用 nextjs 将环境变量部署到 Vercel

node.js - 删除分号时 Nodejs Express API 500 内部服务器错误;

javascript - React Component 成员在渲染后重置为未定义