为何变量api_key未被识别?OpenAI接口请求授权报错
解决api_key在OpenAI请求中未定义的问题
问题原因
你在<head>中使用type="module"的脚本导入了api_key,但模块脚本拥有独立作用域,和下方普通脚本(无type="module"属性)不共享变量,导致点击事件里的代码无法访问到api_key。
解决方案
方案一:合并为模块脚本
将所有逻辑放到同一个模块脚本中,确保变量作用域统一:
<html> <head> </head> <body> </body> <script type="module"> import { api_key } from './file1.js'; console.log(api_key); // 若需要展示密钥,保留这段代码(前提是页面存在id为api_key的元素) // const variableElement = document.getElementById('api_key'); // variableElement.textContent = api_key; let cache = {}; // 确保DOM元素加载完成后再绑定事件 document.addEventListener('DOMContentLoaded', () => { logo1.addEventListener("click", async function() { if (!option1Head.value || option1Head.value === "Option 1" || !idea1.value || idea1.value === "idea 1") { alert("Please write something in the text fields"); return; } const topic = idea.value + option1Head.value; if (cache[topic]) { window.alert(cache[topic]); return; } for (let i = 0; i < bannedKeywords.length; i++) { if (topic.toLowerCase().includes(bannedKeywords[i])) { alert("The topic contains inappropriate content, please try another topic"); return; } } const response = await fetch("https://api.openai.com/v1/engines/text-davinci-003/completions", { method: "POST", headers: { "Content-Type": "application/json", "Authorization": `Bearer ${api_key}` }, body: JSON.stringify({ prompt: `Please generate a text about ${topic}.`, temperature: 0, max_tokens: 188, top_p: 0, frequency_penalty: 0, presence_penalty: 0, }) }); const data = await response.json(); let words = ""; data.choices[0].text.split(" ").forEach(word => { words += word + " "; }); cache[topic] = words; window.alert(words); }); }); </script> </html>
方案二:将api_key挂载到全局对象
如果不想合并脚本,可在模块脚本中将变量挂载到window,让普通脚本能访问:
修改<head>中的模块脚本:
import { api_key } from './file1.js'; console.log(api_key); const variableElement = document.getElementById('api_key'); variableElement.textContent = api_key; // 挂载到全局作用域 window.api_key = api_key;
重要提醒
直接在前端代码中暴露OpenAI的api_key存在严重安全风险,任何人都能通过浏览器开发者工具获取密钥并滥用。建议将请求逻辑移至后端,前端调用自己的后端接口间接请求OpenAI服务。
内容的提问来源于stack exchange,提问作者Sam
相关产品推荐
相关产品推荐

