Localhost在Node.js中找不到,无法在React中获取

brgchamk  于 2023-10-17  发布在  Node.js
关注(0)|答案(1)|浏览(103)

我想使用openai API创建自己的chatgpt。但是当我试着运行我的代码时,我得到了两个错误。第一个是failed to fetch(提交表单后),在端口3000上运行react。第二个是GET http://localhost:3001/chat 404 (Not Found),在我运行服务器的3001端口上。我认为React问题只是因为服务器错误造成的,但我不知道如何修复它。
chat.js

import React, { useState } from "react";

export default function Chat() {
  const [message, setMessage] = useState();
  const [response, setResponse] = useState();

  const handleSubmit = (e) => {
    e.preventDefault();

    fetch("http://localhost:3001/chat", {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify({ message }),
    })
      .then((res) => res.json())
      .then((data) => setResponse(data.message))
      .catch(console.log("Failed to connect"));
  };
  return (
    <>
      <form onSubmit={handleSubmit}>
        <textarea
          value={message}
          onChange={(e) => setMessage(e.target.value)}
        ></textarea>
        <button type="submit">Send</button>
      </form>
      <div>{response}</div>
    </>
  );
}

script.js

const config = require("dotenv").config();
const OpenAI = require("openai");
const openai = new OpenAI({
  apiKey: process.env.OPENAI_API_KEY,
});

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = 3001;

app.use(bodyParser.json());
app.use(cors());

app.post("/chat", async (req, res) => {
  const response = await openai.chat.completions.create({
    model: "gpt-3.5-turbo",
    prompt: "Say this is a test",
    max_tokens: 10,
  });

  if (response.data) {
    if (response.data.choices) {
      res.json({
        message: response.data.choices[0].text,
      });
    }
  }
});

app.listen(port, () => {
  console.log(`server running on port ${port}`);
});

packege.json

{
  "dependencies": {
    "body-parser": "^1.20.2",
    "cors": "^2.8.5",
    "dotenv": "^16.3.1",
    "express": "^4.18.2",
    "openai": "^4.12.1"
  }
}
368yc8dk

368yc8dk1#

我认为这个问题背后的根本原因是CORS政策问题。
我试着在我的机器上运行你的代码
并能够重现问题,但当我改变了cors的政策,如以下我能够作出成功的呼吁

const OpenAI = require("openai");
const openai = new OpenAI({
  apiKey: "Your API Key Here"
});

const express = require("express");
const bodyParser = require("body-parser");
const cors = require("cors");
const app = express();
const port = 3001;

app.use(bodyParser.json());
app.use(cors({ origin: "*" }));

app.post("/chat", async (req, res) => {
  const response = await openai.chat.completions
    .create({
      model: "gpt-3.5-turbo",
      prompt: "Say this is a test",
      max_tokens: 10,
    })
    .catch(() => ({}));

  if (response.data) {
    if (response.data.choices) {
      res.json({
        message: response.data.choices[0].text,
      });
    }
  }
  res.json({
    message: "could not found an answer",
  });
});

app.listen(port, () => {
  console.log(`server running on port ${port}`);
});

相关问题