Next.js调用OpenAI API生成试题时遇TypeError错误求助
问题修复方案
1. 修正API路由函数参数
Next.js App Router的API路由中,POST方法的函数仅接收Request类型的req参数,无需额外声明res参数。更关键的是,你当前的代码仅处理ZodError类型错误,未捕获其他异常,导致服务器抛出未处理错误返回500。
修改POST函数参数定义:
export const POST = async (req: Request) => {
2. 完善全局错误捕获逻辑
补充对所有非ZodError类型错误的处理,避免服务器因未捕获异常崩溃:
catch (error) { if(error instanceof ZodError) { return NextResponse.json({ error: error.issues, }, { status: 400 }) } return NextResponse.json({ error: '服务器内部错误', details: error instanceof Error ? error.message : String(error) }, { status: 500 }) }
3. 处理未匹配的题型分支
当请求的type既不是open_ended也不是mcq时,questions会处于undefined状态,需添加分支返回明确错误:
} else { return NextResponse.json({ error: '不支持的题型类型', }, { status: 400 }) }
4. 排查strict_output函数的headers错误
报错Cannot read properties of undefined (reading 'headers')大概率来自strict_output内部,需检查:
- OpenAI客户端是否正确初始化(如API密钥配置是否有效)
- 函数内部是否错误访问了未定义对象的
headers属性
完整修复后的代码
import { NextResponse } from "next/server" import { quizCreationSchema } from "@/schemas/form/quiz" import { ZodError } from "zod" import { strict_output } from "@/lib/gpt" // POST /api/questions export const POST = async (req: Request) =>{ try { const body = await req.json() const {amount, topic, type} = quizCreationSchema.parse(body) let questions: any; if(type === 'open_ended') { questions = await strict_output( 'You are a helpful AI that is able to generate a pair of questions and answers, the length of the answer should not exceed 15 words, store all the pairs of answers and questions in a JSON array', new Array(amount).fill(`You are to generate a random hard open-ended question about the ${topic}`), { question: "question", answer: "answer with max length of 15 words", } ); } else if(type === 'mcq'){ questions = await strict_output( 'You are a helpful AI that is able to generate mcq questions and answers, the length of each answer should not exceed 15 words', new Array(amount).fill(`You are to generate a random mcq question about ${topic}`), { question: "question", answer: "answer with max length of 15 words", option1: "1st option with max length of 15 words", option2: "2nd option with max length of 15 words", option3: "3rd option with max length of 15 words", } ) } else { return NextResponse.json({ error: '不支持的题型类型', }, { status: 400 }) } return NextResponse.json( { questions }, { status: 200 } ); } catch (error) { if(error instanceof ZodError) { return NextResponse.json({ error: error.issues, }, { status: 400 }) } return NextResponse.json({ error: '服务器内部错误', details: error instanceof Error ? error.message : String(error) }, { status: 500 }) } }
内容的提问来源于stack exchange,提问作者Aritra Chatterjee
相关产品推荐
相关产品推荐

