I have been really struggling with getting this POST request to work when trying out the create chat completion endpoint from the OpenAI API. For context, I began following a YouTube tutorial (Link here but when I got to creating the API route, my postman kept sending me ‘Method not allowed’ errors. Long story short, after several hours of trying to figure out the issue, I have this code that is returning the error message that I set as ‘Something went wrong’.
When I try to complete the Axios request on the client side, it works, but when I try in ‘src/app/api/chat/route.js’ I receive my error.
import axios from "axios";
export async function POST(req) {
try {
const { body } = req;
const url = "https://api.openai.com/v1/chat/completions";
const headers = {
"Content-type": "application/json",
"Authorization": `Bearer ${process.env.NEXT_PUBLIC_OPENAI_API_KEY}`
};
const response = await axios.post(url, body, { headers: headers });
return new Response(JSON.stringify(response.data), { // Pass response.data as the body
status: 201,
headers: {
"Content-Type": "application/json",
"Authorization": `Bearer ${process.env.NEXT_PUBLIC_OPENAI_API_KEY}` // Set the Content-Type header
}
});
} catch (error) {
return new Response('Something went wrong',
{ status: 500 });
}
}
I am expecting my postman to return the OpenAI response.
Any help would be really appreciated – I am very new to coding so apologies for such a noob question!
2
Answers
Try the below solution
201
instead of200
Response
Could you try to generate code of axios from postman because maybe you are missing with some of the headers params.