DeepMagic
DeepMagic

Reputation: 3

React application failing to fetch once publicly hosted

can anyone help me with the following issue? This is all very new to me so I'm sorry for any incoveniences. I'm creating a ChatGPT tool which takes a text inputs from the user in the front end then passes that data into the back end which sends the user input to an open OpenAI API layer. The back end then receives a response back from the OpenAI layer and stores the text response into a text array and writes it back to the front end into a standard text area.

The website runs perfectly when it is hosted locally on localhost:3001 and port:3001. My issue stems when I deploy the website to firebase and attempt to submit a form request on another machine and different network it does not writing any text to the textarea. Below I have provided my code. I believe the issue has something to do with the localhost code in the handleSubmit function or could even be in the back end script i'm very unsure and would really appreciate any help I can get thanks to get this running publicly. Thanks for your time :)

Front End (App.js)

import React, { useState } from 'react';
import './App.css';

function App() {
  const [message, setMessage] = useState('');
  const [response, setResponse] = useState('');

  const handleSubmit = (e) => {
      e.preventDefault();
      fetch('http://localhost:3001', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
      },
      body: JSON.stringify({message}),

    })

      .then((res) => res.json())
      .then((data) => setResponse(data.message));
  };

  return (
    <body>
      <div className="App">
        <form onSubmit={handleSubmit}> 
        <div class="section"></div>
            <header>
              
              <nav>
                <ul class="nav_links">
                  <li><a href='#'>Home</a></li>
                  <li><a href='#'>Pricing</a></li>
                  <li><a href='#'>About</a></li>
                  <li><a href='#'>Contact</a></li>
                </ul>
              </nav>
              <a href="#"><button class="login">Login</button></a>
            </header> 
            
            <input type="text" id="topic"
              value={message}
              onChange={(e) => setMessage(e.target.value)}
            ></input>
            

            <textarea id="textarea" value={response} />

            <div> <button id="generate" type="submit">Generate</button> </div>

        </form>
      </div>
    </body>
    
  );
}

Back End (Index.js)

const OpenAI = require('openai');
const { Configuration, OpenAIApi } = OpenAI;

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

const configuration = new Configuration({
    organization: "org-kEBxx4hVwFZ",
    apiKey: "sk-jmYuTSCZvxCjidnbTpjFT3Blbk",
});
const openai = new OpenAIApi(configuration);
 
app.use(bodyParser.json());
app.use(cors());

app.post('/', async (req, res) => {

    const { message } = req.body;

    const response = await openai.createCompletion({
        model: "text-davinci-003",
        prompt: `${message}`,
        max_tokens: 1000,
        temperature: 0,
      });
    console.log(response.data)
    if(response.data.choices[0].text){
        res.json({message: response.data.choices[0].text})
    }
    
});

app.listen(port, () => {
    console.log("Listening...")
});

Upvotes: 0

Views: 40

Answers (1)

Since http://localhost:3001 is hardcoded into your code, even when you deploy it in production, the production website will still try to make a request to localhost:3001. To fix this, you need to dynamically set the url based on whether the code is in development or production. The recommended way to do this is using environment variables: https://create-react-app.dev/docs/adding-custom-environment-variables/, where you'd set the env variable to localhost:3001 during development and the url of the production server in production.

Upvotes: 1

Related Questions