尝试网络方案后仍无法解决OpenAI API getCompletion报错问题
开发React应用时,调用OpenAI的completions接口持续收到「未提供API密钥」的报错,已在环境中配置有效API密钥,Ai类的getCompletion方法调用逻辑无问题,尝试多种网络方案后仍未解决,多数指向请求头问题。
报错信息
{ "error": { "message": "You didn't provide an API key. You need to provide your API key in an Authorization header using Bearer auth (i.e. Authorization: Bearer YOUR_KEY), or as the password field (with blank username) if you're accessing the API from your browser and are prompted for a username and password. You can obtain an API key from https://platform.openai.com/account/api-keys.", "type": "invalid_request_error", "param": null, "code": null } }
相关代码
export default class Ai { constructor() { this.url = "https://api.openai.com/v1"; this.max_tokens = 2048; this.model = "text-davinci-003"; this.temperature = 0.9; this.top_p = 0; this.apiKey = process.env.REACT_APP_APIKEY; } async getCompletion(prompt) { const path = `${this.url}/completions`; const response = await fetch(`${path}`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${this.apiKey}`, }, body: JSON.stringify({ model: this.model, prompt: prompt, temperature: this.temperature, max_tokens: this.max_tokens, top_p: this.top_p, }), }); try { const data = await response.json(); return data.choices[0].text; } catch (error) { return `${error}`; } } }
排查与解决步骤
验证环境变量加载状态:
React环境变量必须以REACT_APP_开头,确认.env文件放在项目根目录,变量名是REACT_APP_APIKEY。修改.env后必须重启开发服务器,否则变量不会生效。可在Ai类的constructor中添加console.log(this.apiKey),查看控制台是否输出有效密钥(测试后删除该日志,避免密钥泄露)。检查Authorization请求头格式:
确认请求头中Authorization的格式为Bearer 你的API密钥,两者之间有且仅有一个空格。如果this.apiKey为空或未定义,会生成Bearer undefined的无效头,直接导致报错。可在fetch请求前打印headers对象,确认字段值正确。规避客户端密钥暴露风险:
注意:在React客户端直接调用OpenAI API会将密钥暴露给浏览器,存在被盗用的风险。建议搭建后端代理服务,由后端处理OpenAI API请求,前端仅与自有后端交互,从根源保护密钥安全。排查网络拦截因素:
部分开发代理工具、浏览器隐私插件(如广告拦截器)可能会修改或移除请求头。尝试关闭浏览器插件,或在无代理的网络环境下测试,确认请求头是否正常发送。确认API密钥有效性:
登录OpenAI平台检查密钥状态,确认密钥已启用、额度充足且无权限限制。可尝试生成新的API密钥替换原有密钥,排除密钥本身的问题。
内容的提问来源于stack exchange,提问作者Atilla Colak

