参考答案:
前端不应该直接调用 OpenAI 接口并暴露 API Key,推荐通过后端中转调用,确保密钥安全、具备权限控制和请求管理能力。
前端页面
↓ fetch 请求
后端接口(自建中转 API)
↓ 携带 API Key,请求参数控制
OpenAI 接口(如 gpt-3.5)
1// Express 路由示例:/api/chat 2import express from 'express'; 3import fetch from 'node-fetch'; 4 5const router = express.Router(); 6 7router.post('/chat', async (req, res) => { 8 const userMessage = req.body.message; 9 10 const openaiRes = await fetch('https://api.openai.com/v1/chat/completions', { 11 method: 'POST', 12 headers: { 13 Authorization: `Bearer ${process.env.OPENAI_API_KEY}`, 14 'Content-Type': 'application/json', 15 }, 16 body: JSON.stringify({ 17 model: 'gpt-3.5-turbo', 18 messages: [{ role: 'user', content: userMessage }], 19 stream: true, 20 }), 21 }); 22 23 res.setHeader('Content-Type', 'text/event-stream'); 24 openaiRes.body.pipe(res); 25}); 26 27export default router;
1const res = await fetch('/api/chat', { 2 method: 'POST', 3 body: JSON.stringify({ message: '你好' }), 4 headers: { 'Content-Type': 'application/json' }, 5});
1// 不安全的做法(密钥暴露) 2fetch('https://api.openai.com/v1/chat/completions', { 3 headers: { 4 Authorization: 'Bearer sk-xxxx', // 任何人都能拿到 5 }, 6});
问题:
最近更新时间:2026-11-17

题库维护不易,您的支持就是我们最大的动力!