How to Fix 500 Code Server Error Next JS API
P粉513316221
P粉513316221 2023-09-03 21:39:30
0
1
522
<p>I'm trying to build a chatbot using the OPEN AI GPT 4 model in NextJS. However, when I send a POST request to http://localhost:3001/api/generate, I receive a response with status code 500 and the following error message: </p> <blockquote> <p>TypeError: Cannot read property of undefined (read 'header'). </p> </blockquote> <p>/app/api/generate/route.ts</p> <pre class="brush:php;toolbar:false;">import { NextResponse } from "next/server"; import { Configuration, OpenAIApi } from "openai"; const configutation = new Configuration({ apiKey: process.env.OPENAI_API_KEY, }); const openai = new OpenAIApi(configutation); export async function POST(request: Request) { const body = await request.json(); const { prompt } = body; if (!prompt || prompt === "") { return new Response("Please send your prompt", { status: 400 }); } try { const aiResult = await openai.createCompletion({ model: "gpt-4", prompt, temperature: 0.9, max_tokens: 8192, }); const aiText = aiResult.data.choices[0].text?.trim() || "Something went wrong!"; return NextResponse.json({ text: aiText }); } catch (error) { console.log(error); } }</pre> <p>I'm new to NextJS 13, but when I try to send a static response like "Hello World" I don't get any errors</p>
P粉513316221
P粉513316221

reply all(1)
P粉111927962

Next.js API routes expect the request object as the first parameter, not the request object. So you need to change request: Request in your code to req: NextApiRequest . Additionally, you need to change the response object from Response to NextResponse.

For requests, From this

export async function POST(request: Request) {

Here

export default async function generateAPI(req: NextApiRequest) {

For the response, From this

return new Response("Please send your prompt", { status: 400 });

Here

return new NextResponse("Please send your prompt", { status: 400 });
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template