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

NextJS调用OpenAI API无响应,报500内部服务器错误求助

解决Next.js调用OpenAI API返回500内部服务器错误的问题

错误信息

http://localhost:3000/api/chat-gpt net::ERR_ABORTED 500 (Internal Server Error)
onClick @   page.tsx:13
Show 14 more frames

相关代码

/app/(main)/page.tsx

'use client'
import React from 'react';
import Navbar from './_components/navbar';

const HomePage = () => {
  return ( 
    <div className="w-full min-h-full">
      <Navbar />
      <div className="flex flex-col justify-center">
        <h1 className="text-4xl">Welcome to Mood Palette</h1>
        <button
          onClick={async () => {
            const response = await fetch('/api/chat-gpt', {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify({
                message: 'Hello, World!',
              }),
            });
            console.log("Response", response);
          }}
        >
          Create Palette
        </button>
      </div>

    </div>
   );
}
 
export default HomePage;

/app/api/route.ts

import { NextRequest, NextResponse } from "next/server";
import OpenAI from "openai";

const openai = new OpenAI({
    apiKey: `Bearer ${process.env.OPENAI_API_KEY}`,
    project: 'project_id',
});

export async function POST(request: Request) {


    const response = await openai.chat.completions.create({ 
        model: "gpt-3.5-turbo", 
        messages: [
            { role: "system", content: "You are Jarvis from Iron Manl" },
            { role: "user", content: "Who are you?"}
        ],
        temperature: 0,
        max_tokens: 1024,
        top_p: 1,
        frequency_penalty: 0,
        presence_penalty: 0
    });

    return NextResponse.json(response);
}

排查与修复步骤

  • 修正API Key格式:OpenAI SDK初始化时,apiKey不需要Bearer 前缀,直接传入环境变量即可:

    const openai = new OpenAI({
        apiKey: process.env.OPENAI_API_KEY,
        // 若未使用指定项目,可移除project配置,或替换为真实项目ID
        // project: 'your-real-project-id',
    });
    
  • 匹配路由路径:前端请求路径是/api/chat-gpt,但当前后端路由文件/app/api/route.ts对应/api接口。需要将后端路由文件移动到/app/api/chat-gpt/route.ts,确保路径一致。

  • 使用前端传入的请求参数:原后端代码硬编码了用户消息,需从请求体中获取前端发送的message:

    export async function POST(request: Request) {
        const { message } = await request.json();
        const response = await openai.chat.completions.create({ 
            model: "gpt-3.5-turbo", 
            messages: [
                { role: "system", content: "You are Jarvis from Iron Man" }, // 修正拼写错误:Iron Manl → Iron Man
                { role: "user", content: message }
            ],
            // 其他参数保持不变
        });
        return NextResponse.json(response);
    }
    
  • 添加错误捕获与日志:在后端代码中加入错误处理,便于定位具体问题:

    export async function POST(request: Request) {
        try {
            const { message } = await request.json();
            const response = await openai.chat.completions.create({ 
                model: "gpt-3.5-turbo", 
                messages: [
                    { role: "system", content: "You are Jarvis from Iron Man" },
                    { role: "user", content: message }
                ],
                temperature: 0,
                max_tokens: 1024,
                top_p: 1,
                frequency_penalty: 0,
                presence_penalty: 0
            });
            return NextResponse.json(response);
        } catch (error) {
            console.error("OpenAI API调用错误:", error);
            return NextResponse.json({ error: "API调用失败" }, { status: 500 });
        }
    }
    
  • 验证环境变量:确保.env.local文件中正确设置了OPENAI_API_KEY,并且重启了Next.js开发服务器,让环境变量生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.24 21:30:27