React.js 和 OpenAI POST 调用返回 404(未找到)

问题描述 投票:0回答:0

我正在尝试使用以下代码从 App.js 文件调用 API:

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);
}

这是我在 pages/api/generate.js 文件中的内容:

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;
}

在我稍微重组文件并更改脚本之前,这曾经有效,所以这是我的文件结构和脚本:

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

(https://i.stack.imgur.com/yZBzB.png)

现在已经为此工作了好几天,但没有任何效果。与 OpenAI 的连接有效,因为我通过记录模型进行了测试,但问题似乎出在路线上。 谢谢!!!

我尝试重组文件,添加不同的路线、快递和 app.post,但似乎没有任何效果。

reactjs post fetch http-status-code-404 openai-api
© www.soinside.com 2019 - 2024. All rights reserved.