Localhost is not found in Node.js and failed to fetch in React

97 Views Asked by At

I want to create my own chatgpt using openai api. But when i'm trying to run my code i'm getting 2 errors. First one is failed to fetch (after submitting form) on port 3000 where react is running. Second one is GET http://localhost:3001/chat 404 (Not Found) on port 3001 where i'm running my server. I think react problem is only caused because of the server error but I don't know how to fix it.

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"
  }
}
1

There are 1 best solutions below

7
On

I think the root cause behind this problem is the cors policies issues.

I tried running your code on my machine

And was able to reproduce the issue but when I changed the cors policies like following I was able to make a successful call

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