You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Next.js集成ChatGPT:终端获响应但浏览器报401错误求助

Next.js集成ChatGPT出现401错误的解决方案

问题根因

  1. 你直接在组件顶层调用OpenAI API,这段代码会在客户端浏览器环境执行:
    • Next.js默认不会将process.env.API_KEY暴露给客户端,此时API密钥为空,导致OpenAI返回401认证失败
    • OpenAI官方库内部依赖axios发起请求,所以错误栈会显示axios相关信息,哪怕你没直接引入axios
  2. 终端能拿到响应是因为服务端渲染阶段执行了这段代码,此时process.env.API_KEY可正常读取,但客户端渲染时就会出错

修复步骤

1. 规范环境变量配置

修改根目录的.env.local文件,使用规范命名(避免暴露给客户端,不要加NEXT_PUBLIC_前缀):

OPENAI_API_KEY=你的OpenAI密钥

2. 创建服务端API路由代理请求

在pages/api/目录下新建chat.js,通过Next.js API路由处理OpenAI请求(服务端执行,安全获取密钥):

import { Configuration, OpenAIApi } from "openai";

export default async function handler(req, res) {
  // 仅处理POST请求
  if (req.method !== "POST") {
    return res.status(405).json({ error: "仅支持POST请求" });
  }

  const configuration = new Configuration({
    apiKey: process.env.OPENAI_API_KEY,
  });
  const openai = new OpenAIApi(configuration);

  try {
    const response = await openai.createChatCompletion({
      model: "gpt-3.5-turbo",
      messages: [{ role: "user", content: req.body.message }],
    });
    res.status(200).json({ reply: response.data.choices[0].message.content });
  } catch (error) {
    res.status(error.response?.status || 500).json({ 
      error: error.response?.data?.error?.message || error.message 
    });
  }
}

3. 修改前端组件,调用内部API路由

更新Stylebot组件,通过fetch调用自己的API路由,用useState管理响应状态:

import { useState } from "react";

const Stylebot = () => {
  const [reply, setReply] = useState("");
  const [isLoading, setIsLoading] = useState(false);

  const sendChatRequest = async () => {
    setIsLoading(true);
    setReply("");
    
    try {
      const response = await fetch("/api/chat", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({ message: "Hello ChatGPT, how are you?" }),
      });

      const data = await response.json();
      if (response.ok) {
        setReply(data.reply);
      } else {
        console.error("请求失败:", data.error);
      }
    } catch (err) {
      console.error("网络错误:", err);
    } finally {
      setIsLoading(false);
    }
  };

  return (
    <>
      <p>Test ChatGPT</p>
      <button onClick={sendChatRequest} disabled={isLoading}>
        {isLoading ? "正在请求..." : "发送测试消息"}
      </button>
      {reply && <div className="chat-reply">ChatGPT: {reply}</div>}
    </>
  );
};

export default Stylebot;

4. 重要注意事项

  • 禁止在客户端代码中直接使用OpenAI API密钥,否则会被恶意爬取,导致密钥泄露和财产损失
  • Next.js中,只有前缀为NEXT_PUBLIC_的环境变量会暴露给客户端,服务端专用变量不要添加该前缀
  • 若需要支持动态用户输入,只需修改sendChatRequest中传递的message参数即可

内容的提问来源于stack exchange,提问作者Stuart Wallace

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 12:15:25