React应用调用OpenAI API遇400错误及API密钥未识别问题求助
问题概述
React应用调用OpenAI API时遇到两个问题:
- 浏览器控制台弹出
unsafe header 'User-Agent'错误,同时返回400状态码 - OpenAI的
/v1/completions接口返回提示:未提供API密钥,完整错误信息如下:
{ "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 } }
使用的React函数代码:
const configuration = new Configuration({ apiKey: process.env.REACT_APP_OPENAI_API_KEY, organization: "org-xut9Kn1LqNLyDiHEMAQlnJ0k" }); const openai = new OpenAIApi(configuration); const handleSuggestions = async (text) => { const response = await openai.createCompletion({ model: "text-davinci-001", prompt: "autocomplete this word, letter or sentence: " + text, max_tokens: 100, n: 1, stop: text.length - 1, temperature: 0.15, }); console.log(response); const data = await response.json(); setSuggestions(response.choices[0].text.split(' ').slice(text.split(' ').length - 1).join(' ').split(' ')); };
问题分析与解决办法
1. API密钥未传递的问题
- 原因:
.env文件变量未正确加载,导致process.env.REACT_APP_OPENAI_API_KEY为空;- OpenAI官方SDK在浏览器环境下,会被浏览器安全策略拦截部分请求头,导致Authorization头未正确传递。
- 解决步骤:
- 确认
.env放在项目根目录,变量名必须以REACT_APP_开头,格式为REACT_APP_OPENAI_API_KEY=你的密钥,修改后重启开发服务器; - 优先使用后端代理:搭建Node.js后端接口,在后端调用OpenAI API,前端请求自己的后端接口,彻底规避浏览器的请求头限制;
- 临时测试可改用
fetch手动发送请求,避免SDK自动添加受限请求头:const handleSuggestions = async (text) => { try { const response = await fetch('https://api.openai.com/v1/completions', { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': `Bearer ${process.env.REACT_APP_OPENAI_API_KEY}` }, body: JSON.stringify({ model: "text-davinci-001", prompt: `autocomplete this word, letter or sentence: ${text}`, max_tokens: 100, n: 1, // 修正stop参数:改为字符串或数组,比如设置为换行符 stop: ["\n"], temperature: 0.15, }) }); const data = await response.json(); if (data.choices) { const suggestion = data.choices[0].text.split(' ').slice(text.split(' ').length - 1).join(' ').split(' '); setSuggestions(suggestion); } } catch (err) { console.error(err); } };
- 确认
2. unsafe header 'User-Agent'错误
- 原因:OpenAI SDK默认会添加自定义User-Agent请求头,浏览器安全策略禁止修改该请求头,因此报错。
- 解决办法:
- 用后端代理彻底规避;
- 改用手动
fetch请求,不设置User-Agent头,使用浏览器默认值即可。
3. 代码中的其他错误
stop参数错误:该参数要求是字符串或字符串数组,你传入的text.length - 1是数字,会导致API参数无效,触发400错误,需改为合理的停止字符串;- SDK返回值处理错误:
openai.createCompletion返回的是SDK封装的对象,无需调用response.json(),直接通过response.data获取结果,当前代码会导致response.json()报错。
是否属于可复现的最小示例?
不属于。可复现的最小示例需要满足:
- 移除非必要代码(比如
organization参数,若不是必须的话); - 简化结果处理逻辑,只保留核心请求代码;
- 明确
.env配置说明,确保变量加载逻辑清晰; - 修正无效参数(比如错误的
stop参数),避免干扰核心问题的复现。
内容的提问来源于stack exchange,提问作者udenx10
相关产品推荐
相关产品推荐

