OpenAI GPT-3 API调用报错排查:前端JS代码问题还是CORS限制?
问题分析与解决方案
你的问题同时存在代码错误和CORS限制两个问题,具体分析和解决方法如下:
一、代码本身的错误点
- API端点路径错误:你使用的
https://api.openai.com/v1/engines/davinci-codex/completions是旧版引擎专属端点,但请求里指定的模型是text-davinci-003,两者不匹配。正确的通用补全端点应为https://api.openai.com/v1/completions。 - Authorization头格式错误:密钥被多余的单引号包裹,正确格式是
Authorization: "Bearer YOUR_API_KEY",单引号会导致API识别无效密钥。 - 参数冲突:路径里的
davinci-codex和请求体里的text-davinci-003模型冲突,必须去掉路径中的引擎指定。
二、CORS限制问题
直接在浏览器前端调用OpenAI API必然触发CORS错误,因为OpenAI的API服务器未配置允许前端域名的跨域请求。解决方式是搭建后端代理服务:前端请求自己的后端接口,再由后端转发请求到OpenAI API。
修正后的前端代码示例
function generateOutput() { var userInput = document.getElementById("input").value; // 请求自己的后端代理接口 fetch("/api/openai/completions", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ prompt: userInput, max_tokens: 50, model: "text-davinci-003" }), }) .then(response => { if (response.ok) { return response.json(); } else { throw new Error("API请求失败"); } }) .then(data => { const output = data.choices[0].text.trim(); document.getElementById("output").textContent = output; }) .catch(error => { document.getElementById("errorMessage").textContent = "请求出错:" + error.message; }); }
后端代理示例(Node.js/Express)
const express = require('express'); const fetch = require('node-fetch'); const app = express(); const PORT = 3000; app.use(express.json()); app.post('/api/openai/completions', async (req, res) => { try { const response = await fetch('https://api.openai.com/v1/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer YOUR_API_KEY` // 替换为你的OpenAI密钥 }, body: JSON.stringify(req.body) }); const data = await response.json(); res.json(data); } catch (error) { res.status(500).json({ error: error.message }); } }); app.use(express.static('public')); // 托管前端静态文件目录 app.listen(PORT, () => { console.log(`服务器运行在端口 ${PORT}`); });
内容的提问来源于stack exchange,提问作者shon
相关产品推荐
相关产品推荐

