swiftieDev
swiftieDev

Reputation: 1

React.js and OpenAI POST call returns 404 (not found)

I am trying to call the API from the App.js file with the following code:

async function onSubmit(event) {
  if (event) {
    event.preventDefault();
  }
  const response = await fetch("/api/generate", {
    method: "POST",
    headers: {
      "Content-Type": "application/json",
    },
    body: JSON.stringify({ headline: openAIInstructions }),
  });
  const data = await response.json();
  setResult(data.result);
  console.log(currentRound);
}

And here is what I have in the pages/api/generate.js file:

import { Configuration, OpenAIApi } from "openai";

const configuration = new Configuration({
  apiKey: process.env.REACT_APP_OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);

export default async function (req, res) {
  const completion = await openai.createCompletion("text-davinci-002", {
    prompt: generatePrompt(req.body.headline),
    temperature: 1,
    max_tokens: 200,
  });
  const responseData = { result: completion.data.choices[0].text };
  res.setHeader("Content-Type", "application/json");
  res.status(200).send(JSON.stringify(responseData));
}

function generatePrompt(headline) {
  return headline;
}

This used to work before I restructured the files a bit and changed the scripts, so here is my file structure and scripts:

"scripts": {
  "dev": "NODE_OPTIONS=--openssl-legacy-provider",
  "start": "react-scripts start",
  "build": "react-scripts build",
  "deploy": "serve -s build"
}

(https://i.sstatic.net/yZBzB.png)

Being working on this for days now and nothing works. The connection to OpenAI works because I tested by logging the models, but the problem seems to be the route. Thank you!!!

I tried restructuring the files, adding different routes, express and app.post and nothing seems to work.

Upvotes: 0

Views: 210

Answers (1)

swiftieDev
swiftieDev

Reputation: 1

I fixed the issue after @picsoung asked me what framework I was using. I realized that I was trying to use Next.js while my scripts were designed for CRA (Create React App). After I reorganized my scripts and folders to run as a Next.js framework, everything worked. Thanks and my apologies.

Upvotes: 0

Related Questions