在部署的应用程序上播放来自 s3 的文件时出现跨源资源策略问题

问题描述 投票:0回答:2

我在 Heroku 上部署了一个应用程序,可以让我播放音频文件。您可以在这里查看https://telecurve.herokuapp.com/manage。在我在 Heroku 中播放文件没有问题之前,但在修改了 server.js 文件之后(我的应用程序是一个 Express 应用程序,使用内置的 Create React 应用程序部署),我收到此错误。您可以尝试播放音频文件并查看响应。但是,我仍然可以使用下载按钮从 s3 下载文件,没有任何问题。

这是一些相关代码:

server.js

    require('rootpath')();
    const path = require('path');
    const express = require('express');
    const app = express();
    const bodyParser = require('body-parser');
    const cookieParser = require('cookie-parser');
    const cors = require('cors');
    
    app.use(bodyParser.urlencoded({ extended: false }));
    app.use(bodyParser.json());
    app.use(cookieParser());
    
    // Have Node serve the files for our built React app
    app.use(express.static(path.resolve(__dirname, 'build')));
    
    // allow cors requests from any origin and with credentials
    app.use(cors({ origin: (origin, callback) => callback(null, true), credentials: true }));
    
   //change added that caused issues with the playing mechanism. Needed these headers for another 
    app.use(function(req, res, next) {
      res.header("Cross-Origin-Embedder-Policy", "require-corp");
      res.header("Cross-Origin-Opener-Policy", "same-origin");
      next();
    });
    
    
    // file api routes
    app.use('/accounts', require('./accounts/accounts.controller'));
    
    
    // All other GET requests not handled before will return our React app
    app.get('*', (req, res) => {
        res.sendFile(path.resolve(__dirname, 'build', 'index.html'));
    });
    
    app.get('/app', async (req, res) => {
      res.sendFile(path.join(__dirname, 'public/index.html'));
    });
    // does work, cors headers in response as expected
    
    
    // start server
    const port = process.env.PORT || 2000;
    app.listen(port, () => console.log('Server listening on port ' + port));

这是我在 server.js 中添加的特定更改:

   //change added that caused issues with the playing mechanism. Needed these headers for another 
    app.use(function(req, res, next) {
      res.header("Cross-Origin-Embedder-Policy", "require-corp");
      res.header("Cross-Origin-Opener-Policy", "same-origin");
      next();
    });

也许我需要为 s3 添加额外的标头?

我最近还删除了这段代码:

app.use(function(req, res, next) {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept");
  next();
});

这是我在后端的预签名方法,我用它来生成播放/下载的网址:

  const customer_id = data['customer-id'];
  const sound_id = data['sound-id'];
  
  return new Promise((resolve, reject) => {
    //get presigned url

    var myBucket = process.env.NODE_APP_BUCKET_NAME;
    var myKey = "sounds/" + customer_id + "/" + sound_id + ".wav"; 
    const signedUrlExpireSeconds = 120;
    try {
      const url = s3.getSignedUrl('getObject', {
        Bucket: myBucket,
        Key: myKey,
        ResponseContentDisposition: 'attachment',
        Expires: signedUrlExpireSeconds
      });
      resolve(url)
    }
    catch {
      console.log('S3 Object does not exist');
      resolve('');
    }
  });

然后我获取此 url,使用

var audio = new Audio(url)
创建一个新的音频对象并播放它。

如果您发现任何问题或我缺少任何内容,请告诉我。

node.js reactjs amazon-s3 cors cross-origin-resource-policy
2个回答
6
投票

您似乎直接使用指向 S3 上音频文件的 URL,这意味着:

当我写这篇文章时,你的应用程序已关闭,因此我无法实际验证它是由 S3 跨域资源引起的,但根据你的问题,这是最有可能的问题。


0
投票

遇到了同样的问题。

这里是如何解决的:

const audio = "your audio tag";
const audio_src = audio.src;
fetch(audio_src, { mode: 'cors' })
    .then(response => response.blob())
    .then(blob => {
        const url = URL.createObjectURL(blob);
        audio.src = url;
        audio.play();
    })
    .catch(error => console.error('Error fetching audio:', error));
© www.soinside.com 2019 - 2024. All rights reserved.