这个错误提示表明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'`可能会导致你无法获取响应的内容,因为浏览器会返回一个不透明的响应。这个解决方案只在你不需要读取响应内容时有效。如果你需要处理响应数据,那么前两种解决方案会更合适。