我有一个有效的 NodeJS 代码,它向本地 OpenAI API 上的
/audio/transcriptions
端点发出请求。
该文件给出为
fs.createReadStream("speech.m4a")
。
节点应用程序完美运行,给出输出:
{text: "<the transcription of the speech>"}
但是,当我想要执行完全相同的请求,但使用输入字段而不是硬编码文件时,我会收到 AxiosError 并显示消息“网络错误”。
我尝试像这样调用axios.post:
const API_URL = "http://172.26.175.134:8080/openai/v1/audio/transcriptions";
const fileInput = document.getElementById("file-input");
fileInput.onchange = () => {
const files = fileInput.files;
//if no file is selected
if (files.length === 0) {
alert("Please select a file!");
return;
}
const selectedFile = files[0];
const reader = new FileReader();
reader.onload = (e) => {
axios
.post(
API_URL,
{
file: new File([e.target.result], { type: selectedFile.type }),
model: "whisper",
language: "en",
temperature: 1,
prompt: "",
},
{
headers: {
"Content-Type": "multipart/form-data",
},
}
)
.then((response) => {
console.debug(response.data);
})
.catch((error) => {
console.error("Error:", error);
});
};
reader.readAsArrayBuffer(selectedFile);
};
结果是一样的,我得到相同的 AxiosError 消息为
Network error
。
我还注意到响应是 200 OK,因此生成了文字记录。
API 响应:
INFO: 172.26.160.1:62548 - "POST /openai/v1/audio/transcriptions HTTP/1.1" 200 OK
后端响应:
INFO:faster_whisper:Processing audio with duration 00:19.925
INFO:faster_whisper:Detected language 'en' with probability 1.00
INFO:__main__:Completed /tmp/tmpswy0__ru
INFO:__main__:Transcription complete!
更新:我也从 axios 切换到 fetch,它仍然是一个有效的请求(响应是 200 OK),但我仍然无法获取响应
reader.onload = async (e) => {
const body = new FormData();
body.append(
"file",
new File([e.target.result], { type: selectedFile.type })
);
body.append("model", "whisper");
body.append("language", "en");
body.append("temperature", "1");
body.append("prompt", "");
await fetch(API_URL, {
method: "POST",
body: body,
})
.then((res) => {
console.debug(res);
})
.catch((err) => {
console.debug(err);
});
};
TypeError: Failed to fetch at reader.onload
我的问题是:什么会导致此请求出现问题? 你在客户端 axios 上遇到过这个问题吗? 感谢您提前的帮助。
我已通过修复 API 端的 CORS 错误成功解决了该问题。我必须将以下几行(尤其是
allow_origins=["*"]
)添加到 API 代码(用 Python 编写的 FastAPI)
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)