- API Call failed: Error code: 404 - {'error': {'message': 'Invalid URL (POST /v...
错误信息
2026-08-19 17:31:09,190 - ERROR - API Call failed: Error code: 404 - {'error': {'message': 'Invalid URL (POST /v1/chat/completions/chat/completions)', 'type': 'invalid_request_error', 'param': '', 'code': ''}}
AI 解决方案
🔍 报错分析
1. 🌐 错误翻译
原文:Error code: 404 - {'error': {'message': 'Invalid URL (POST /v1/chat/completions/chat/completions)', 'type': 'invalid_request_error', 'param': '', 'code': ''}}
译文:错误代码:404 - {'error': {'message': '无效的URL (POST /v1/chat/completions/chat/completions)', 'type': '无效请求错误', 'param': '', 'code': ''}}
2. 🎯 原因分析
- 根本原因:API请求的URL路径重复拼接,导致构造了无效的请求地址
/v1/chat/completions/chat/completions - 具体位置:在发起聊天完成API请求时,请求路径被错误地拼接了两次
/chat/completions部分 - 错误类型:HTTP 404 错误,表示服务器无法找到请求的资源,直接原因是URL格式错误
3. 💡 解决方案
检查并修复API请求的URL拼接逻辑,确保只保留一次正确的路径 /v1/chat/completions:
``代码语言
// 错误示例(重复拼接路径)
const incorrectUrl = "https://api.example.com/v1/chat/completions" + "/chat/completions";
// 修复后的正确代码
const correctUrl = "https://api.example.com/v1/chat/completions";
// 发起请求示例
const response = await fetch(correctUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
"Authorization": "Bearer YOUR_API_KEY"
},
body: JSON.stringify({
model: "gpt-3.5-turbo",
messages: [{ role: "user", content: "Hello" }]
})
});
`
4. 🛡️ 预防措施
- 规范URL构造方式:使用统一的基础URL配置,通过常量或配置文件管理API端点,避免硬编码和手动拼接;例如将基础URL定义为 const BASE_URL = "https://api.example.com/v1"
,需要时拼接具体接口const url =${BASE_URL}/chat/completions - 引入类型检查与校验:使用TypeScript等强类型语言,或封装API请求工具类,对最终拼接的URL进行格式校验,可在发送请求前输出URL进行核对,及时发现路径重复或拼写错误
- 测试环节覆盖:针对API请求的URL编写单元测试,验证各接口URL格式的正确性,确保拼接逻辑符合规范。