React应用在公开托管后无法获取数据。

huangapple go评论69阅读模式
英文:

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 :)"

请注意,这段内容较长,只能提供有限的翻译。如果您需要特定部分的翻译或有任何其他问题,请告诉我。

英文:

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 React应用在公开托管后无法获取数据。

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

答案1

得分: 1

由于http://localhost:3001被硬编码到您的代码中,即使在生产环境部署时,生产网站仍会尝试向localhost:3001发出请求。要解决此问题,您需要根据代码是在开发环境还是生产环境中运行,动态设置URL。推荐的方法是使用环境变量:https://create-react-app.dev/docs/adding-custom-environment-variables/,在开发期间将环境变量设置为localhost:3001,在生产环境中设置为生产服务器的URL。

英文:

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.

huangapple
  • 本文由 发表于 2023年1月6日 02:17:09
  • 转载请务必保留本文链接:https://go.coder-hub.com/75022741.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定