这段代码 async function toDownLoadAudio() { if (currentAudio.v

动态 未结 0 23
邮箱用户_r5u2k
邮箱用户_r5u2k LV1 2月18日 22:55 发表
摘要:
这段代码 async function toDownLoadAudio() { if (currentAudio.value === '') return try { const fileName = currentAudio.value.split('/').pop() // 获取最后一个斜杠后的部分作为文件名 const response = await fetch(currentAudio.value) if (!response.ok) throw new Error('未能获取音频文件') const blob = await response.blob() const url = URL.createObjectURL(blob) const aLink = document.createElement('a') aLink.href = url aLink.download = fileName // 替换为实际文件名 aLink.style.display = 'none' document.body.appendChild(aLink) aLink.click() // 清理 URL.revokeObjectURL(url) document.body.removeChild(aLink) } catch (error) { console.error('下载音频时发生错误:', error) } } 提示这个 ccess to fetch at 'https://storage.googleapis.com/udio-artifacts-c33fe3ba-3ffe-471f-92c8-5dfef90b3ea3/samples/dde3aaa27d7a4f8da96354d4a7986b49/1/The%2520Untitled.mp3' from origin 'http://localhost:1002' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. 我的前端代码使用的vue+ts
这个错误提示表明CORS(跨源资源共享)策略阻止了你的网页从指定的源(`https://storage.googleapis.com/...`)获取资源。这是因为目标服务器没有在响应中包含`Access-Control-Allow-Origin`头,或者它的值没有包含你的源(`http://localhost:1002`)。 为了解决这个问题,你有几个选择: 1. **服务器端解决**:最合适的解决方案是在服务器端添加适当的CORS头。如果你有访问服务器设置的权限,可以添加`Access-Control-Allow-Origin`头,允许你的源访问资源。 2. **使用代理服务器**:如果你无法直接修改目标服务器的设置,可以在你的服务器上设置一个代理,它会添加必要的CORS头,并将请求转发到目标服务器。 3. **修改请求模式**:在你的前端代码中,你可以尝试将`fetch`请求的模式设置为`'no-cors'`。请注意,这样做会有一些限制,例如你只能接收一个不透明的响应,不能读取响应内容。 下面是修改后的代码,展示如何设置`fetch`请求的模式为`'no-cors'`: ```typescript async function toDownLoadAudio() { if (currentAudio.value === '') return try { const fileName = currentAudio.value.split('/').pop() // 获取最后一个斜杠后的部分作为文件名 const response = await fetch(currentAudio.value, { mode: 'no-cors' }) if (!response.ok) throw new Error('未能获取音频文件') const blob = await response.blob() const url = URL.createObjectURL(blob) const aLink = document.createElement('a') aLink.href = url aLink.download = fileName // 替换为实际文件名 aLink.style.display = 'none' document.body.appendChild(aLink) aLink.click() // 清理 URL.revokeObjectURL(url) document.body.removeChild(aLink) } catch (error) { console.error('下载音频时发生错误:', error) } } ``` 请注意,将请求模式设置为`'no-cors'`可能会导致你无法获取响应的内容,因为浏览器会返回一个不透明的响应。这个解决方案只在你不需要读取响应内容时有效。如果你需要处理响应数据,那么前两种解决方案会更合适。
收藏(0)  分享
相关标签: 智能问答
问题没解决?让AI助手帮你作答 AI助手
0个回复
  • 消灭零回复