Azure OpenAI代理URL截断致404错误技术求助
问题分析与解决方法
你的核心问题是Axios的URL拼接规则导致请求路径错误,进而返回404。
具体原因
你设置的baseURL为"https://[REDACTED].azure.com/openai/deployments"(末尾无斜杠),而endpoint为"/gpt-4o/chat/completions?api-version=2024-08-01-preview"(开头带斜杠)。根据Axios的URL拼接逻辑:当请求路径以斜杠开头时,会替换掉baseURL的路径部分,只保留域名。实际错误中路径未被替换反而丢失了/gpt-4o/chat/completions,本质是Axios对带查询参数的路径拼接处理异常,导致有效路径被忽略。
修复步骤
1. 修正URL拼接方式
任选以下一种方式调整,确保生成正确的请求URL:
- 方式一:给
baseURL添加末尾斜杠const baseURL = "https://[REDACTED].azure.com/openai/deployments/"; // 末尾加/ const endpoint = "/gpt-4o/chat/completions?api-version=2024-08-01-preview"; // 保留开头/ - 方式二:去掉
endpoint开头的斜杠const baseURL = "https://[REDACTED].azure.com/openai/deployments"; // 保持不变 const endpoint = "gpt-4o/chat/completions?api-version=2024-08-01-preview"; // 去掉开头/
两种方式最终都会生成正确的请求地址:https://[REDACTED].azure.com/openai/deployments/gpt-4o/chat/completions?api-version=2024-08-01-preview
2. 移除无效的响应判断
代码中if (isAxiosError(openaiResponse))完全无效——Axios请求成功时返回的是响应对象,而非错误,错误会直接进入catch块。删除这段判断,简化代码:
// 替换原错误判断逻辑 response.status(200).send(openaiResponse.data);
3. 确保请求体合法
测试时要保证客户端传入的request.body包含Azure OpenAI要求的字段(如你curl命令中的messages数组),避免因空请求体导致额外错误。
完整修复后的代码
import { onRequest } from "firebase-functions/v2/https"; import axios from "axios"; export const azureOpenaiProxy = onRequest(async (request, response) => { try { const apiKey = "[REDACTED]"; const baseURL = "https://[REDACTED].azure.com/openai/deployments"; const endpoint = "gpt-4o/chat/completions?api-version=2024-08-01-preview"; const axiosInstance = axios.create({ baseURL }); const openaiResponse = await axiosInstance.post(endpoint, request.body, { headers: { "api-key": apiKey, "Content-Type": "application/json", }, }); response.status(200).send(openaiResponse.data); } catch (error) { response.status(500).json({ error: "Internal server error", message: error instanceof Error ? error.message : "Unknown error", }); } });
内容的提问来源于stack exchange,提问作者Nana Kwame
相关产品推荐
相关产品推荐

