skip to Main Content

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


  1. Try the below solution

    In your code exist two problems

    1. status code return 201 instead of 200
    2. no need to wrap the response with a new Response
    import axios from 'axios';
    
    export default async function handler(req, res) {
        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 })
          res.status(200).json(response.data);
        } catch (error) {
          console.log(error);
          res.status(500).json({ message: "Something went wrong" });
        }
      } 
    }
    
    Login or Signup to reply.
  2. Could you try to generate code of axios from postman because maybe you are missing with some of the headers params.

    enter image description here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search