How to Fix 500 Code Server Error Next JS API
P粉513316221
2023-09-03 21:39:30
<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>
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 toreq: NextApiRequest
. Additionally, you need to change the response object from Response to NextResponse.For requests, From this
Here
For the response, From this
Here