React+Axios开发类ChatGPT应用调用OpenAI API遇404错误求助
问题定位与修复方案
你的404错误来自后端调用OpenAI API时的请求错误,核心问题是使用了已废弃的Completion API端点和模型,而你实际要调用的是Chat Completions API,两者的URL、请求体格式完全不同。
具体修复步骤
1. 替换OpenAI API端点和模型
将后端中调用OpenAI的URL从旧的Completion端点:
"https://api.openai.com/v1/engines/davinci-codex/completions"
替换为Chat Completions的正确端点:
"https://api.openai.com/v1/chat/completions"
同时使用Chat模型(比如gpt-3.5-turbo,这是ChatGPT的基础模型),而不是已弃用的davinci-codex。
2. 调整请求体格式
Chat Completions API不使用prompt参数,而是需要传递messages数组,每个消息包含role(user/assistant/system)和content字段。
3. 修改响应数据解析逻辑
Chat Completions的响应结构和旧的Completion不同,需要从response.data.choices[0].message.content中提取回复内容,而不是response.data.choices[0].text。
修正后的后端代码(index.js)
const express = require("express"); const axios = require("axios"); const cors = require("cors"); const app = express(); app.use(express.json()); app.use(cors()); const openai_api_key = "MYOPENAI-APIKEY"; const headers = { "Content-Type": "application/json", "Authorization": `Bearer ${openai_api_key}`, }; app.post("/api/chat", async (req, res) => { try { const input = req.body.text; const response = await axios.post( "https://api.openai.com/v1/chat/completions", // 修正后的URL { model: "gpt-3.5-turbo", // 使用Chat模型 messages: [ { role: "user", content: input } // 调整为messages数组格式 ], max_tokens: 150, temperature: 0.7, n: 1, }, { headers } ); // 修正响应解析路径 const gptResponse = response.data.choices[0].message.content.trim(); res.json({ message: gptResponse }); } catch (error) { console.error("OpenAI API Error:", error.response?.data || error.message); res.status(500).json({ error: "An error occurred while processing your request." }); } }); const PORT = process.env.PORT || 5000; app.listen(PORT, () => { console.log(`Server started on port ${PORT}`); });
额外检查点
- 确保你的OpenAI API密钥有权限访问
gpt-3.5-turbo模型(大部分免费/付费账号默认都有)。 - 如果前端到后端的请求也出现404,确认后端服务确实在
localhost:5000运行,并且没有路由拼写错误。
内容的提问来源于stack exchange,提问作者babybirkins
相关产品推荐
相关产品推荐

