gpt4 book ai didi

javascript - 用于访问另一个域上的文件的 CORS header

转载 作者:行者123 更新时间:2023-11-30 15:37:27 26 4
gpt4 key购买 nike

我正在尝试在 Codepen 上创建一个音频可视化程序。我用 apache 创建了自己的 Ubuntu 网络服务器,它允许我直接访问修改服务器的 header 和配置。

虽然浏览器可以访问不同域上的文件,但它需要特殊的 CORS header 来读取音频中的频率。要读取音频频率,我必须使用 createMediaElementSource 来访问包括频率在内的音频信息。当浏览器看到这个 JavaScript 方法时,它知道必须在服务器上设置某些 header 才能允许访问。这让我们想到了这个问题的动机:需要设置哪些 header ?

我测试过的所有浏览器都会返回 CORS 错误的变体。尽管我已经在 Chrome、Opera 和 Safari 中测试过它并得到类似的结果,但它在 Firefox 中看起来像这样:

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://williamgreen.hopto.org/audioVisualization/song.mp3. (Reason: CORS header ‘Access-Control-Allow-Origin’ does not match ‘(null)’).

文件返回 206 部分内容。以下是返回的服务器 header (当前): Audio file returned headers以下是发送的 header (当前): audio file send headers

function log(text) {
document.getElementById("log").textContent += text + "\n";
}

var audio, source, context;
var url = "http://williamgreen.hopto.org/audioVisualization/song.mp3";

document.addEventListener("DOMContentLoaded", function() {
log("URL: " + url);

log("Creating Audio instance from audio file");
audio = new Audio(url);
audio.crossOrigin="anonymous";

audio.addEventListener("canplay", function() {
log("Playing audio file through HTML5 Audio for 3 seconds");
audio.play();

setTimeout(function() {
log("Creating Web Audio context");
context = new (typeof AudioContext != "undefined" ? AudioContext : webkitAudioContext)();

log("Calling createMediaElementSource on audio (switching to Web Audio)");
source = context.createMediaElementSource(audio);

setTimeout(function() {
log("Connecting source to context destination");
source.connect(context.destination);

log("\nIf no sound can be heard right now, the problem was reproduced.");
}, 1000);
}, 3000);
});
});
<div id="log"></div>

我需要更改什么才能使其正常工作?

最佳答案

我首先想到的是你的问题

Access-Control-Allow-Origin: *, *

我不认为这是理解 *, * 的事情。试试 *

编辑:您可以使用如下命令检查 header 的真实外观:

curl -v -o /dev/null http://williamgreen.hopto.org/audioVisualization/song.mp3

而且,瞧,它甚至对我有用,产生(在许多其他 header 中):

< Access-Control-Allow-Origin: *

所以这就是 hunky-dory。

其次,您是否从 file: 源运行它?这在 Chrome 上不起作用(我认为它会在 Firefox 上起作用,但也许已经改变了)。您必须从 http:https: 来源运行它。

我的意思是“从文件运行:来源”,是指运行该 Javascript 的 HTML 文件是从带有“文件:”的 URL 加载的。如果是这样,那不太可能奏效。

关于javascript - 用于访问另一个域上的文件的 CORS header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41306459/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com