-1

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.

When I console.log the error in the catch block, I receive this axios error: AxiosError: Request failed with status code 400 at settle (webpack-internal:///(rsc)/./node_modules/axios/lib/core/settle.js:21:16)

Any help would be really appreciated - I am very new to coding so apologies for such a noob question!

2 Answers2

0

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" });
    }
  } 
}
xgqfrms
  • 10,077
  • 1
  • 69
  • 68
-1

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

Trushar Narodia
  • 3,511
  • 2
  • 11
  • 17
  • `const axios = require('axios'); let data = JSON.stringify({ "model": "gpt-4", "messages": [ { "role": "user", "content": "Hello" } ] }); let config = { method: 'post', maxBodyLength: Infinity, url: 'http://localhost:3000/api/chat', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer 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' }, data : data }; axios.request(config) .then((response) => { console.log(JSON.stringify(response.data)); }) .catch((error) => { console.log(error); });` – Veronica Atkinson-Rojas Aug 29 '23 at 10:08