1

Summary: I am trying to teach myself Flask and React with the tools I have at hand during the pandemic. I am hampered by the lack of a good React editor for remote files, I suspect I may not be seeing error messages such an editor would be showing me, and I suspect that the python script I am trying to invoke is never getting touched.

Any help, including how to better see error messages, or what might be mis-configured, are desperately appreciated.

What I have:

  1. A command line only interface to an Ubuntu 18.04 container. This means: no remote desktop, no GUI, no specialized react editor. I cannot do anything about this.

  2. React server up and running on container port 3000, accessible to the outside world with a path prefix per this question and answer. Meaning, I can run react from the text terminal command line, edit react project files in another window with vi, point a browser to it from well outside the system and it works.

  3. Flask server up and running on container port 3001 (port 5000 already doing something else) and React server configured with port 3001 as a proxy. God help me, I am using the DANGEROUSLY_DISABLE_HOST_CHECK option to get that to work. No special consideration for port prefixing or port forwarding-- this seems all internal to the container, so I don't think any special handling is necessary.

  4. A tutorial project as per this site. I will include the two relevant code files below.

The results of this are:

  • No errors in either of the terminals where I invoked the react and flask servers.

  • The web page displays, but improperly: Rather than displaying the correct time, the page displays only whatever I pre-loaded into currentTime.

  • I am highly skeptical that the python script is ever running at all: If I mangle the api.py file with egregious syntactical errors... no change in behavior. If I mangle the App.js with errors, the system dies. If I mangle the App.js with the specific error of fetch('/garbage').then... rather than fetch('/time').then... there are still no errors, which I find HIGHLY suspicious.

  • This makes me think I may not be seeing some critical error or warning messages.

  • My suspicion was that this might be some type of CORS issue, but two attempts at adapting solutions to this question failed.

Code from App.js:

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

function App() {
  const [currentTime, setCurrentTime] = useState(2);

  useEffect(() => {
    fetch('/time').then(res => res.json()).then(data => {
      setCurrentTime(data.time);
    });
  }, []);

  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
        <p>The current time is {currentTime}.</p>
      </header>
    </div>
  );
}

export default App;

Code from api.py (not including CORS attempts):

import time
from flask import Flask

app = Flask(__name__)

@app.route('/time')
def get_current_time():
    return {'time': time.time()}

UPDATE:

On the advice of this answer, I added some console logging statements and looked at the console logging in Chrome.

App.js:11 GET http://<CORRECT_ADDRESS>/time 404 (Not Found)
(anonymous) @ App.js:11
commitHookEffectListMount @ react-dom.development.js:19731
commitPassiveHookEffects @ react-dom.development.js:19769
callCallback @ react-dom.development.js:188
invokeGuardedCallbackDev @ react-dom.development.js:237
invokeGuardedCallback @ react-dom.development.js:292
flushPassiveEffectsImpl @ react-dom.development.js:22853
unstable_runWithPriority @ scheduler.development.js:653
runWithPriority$1 @ react-dom.development.js:11039
flushPassiveEffects @ react-dom.development.js:22820
(anonymous) @ react-dom.development.js:22699
workLoop @ scheduler.development.js:597
flushWork @ scheduler.development.js:552
performWorkUntilDeadline @ scheduler.development.js:164

Note 1: Port 3001 is not included, which seems wrong. Note 2: The path prefix is not included, which seems correct.

I would have expected this to be: App.js:11 GET http://<CORRECT_ADDRESS>:3001/time

If the port, and not the path prefix, needs to be included in that call, how do I arrange that?

Flask is running on port 3001, and the last line of package.json is:

"proxy": "http://localhost:3001"


Further Update:

using fetch('http://<CORRECT_ADDRESS>:3001/time') now yields the following console errors:

WebSocket connection to 'ws://<CORRECT_ADDRESS>/sockjs-node' failed: Error during WebSocket handshake: Unexpected response code: 404
The development server has disconnected.
Refresh the page if necessary.
GET http://<CORRECT_ADDRESS>:3001/time net::ERR_CONNECTION_TIMED_OUT
Uncaught (in promise) TypeError: Failed to fetch

So the GET seems to be well-formed, now, but times out due to the failed WebSockets call, which may or may not be correctly formed.

Novak
  • 4,687
  • 2
  • 26
  • 64

1 Answers1

1

You may be seeing an infinite loop, where state is not having a chance to update.

Try this:

@app.route('/time')
def get_current_time():
    print( time.time() )
    return {'time': time.time()}

Is /time getting hits? Because your useEffect() code will run every time the state changes, which is every time it runs: infinite loop.

If /time is not getting hits, then your problem is in that relative path. Try this:

useEffect(() => {
    console.log('fetching');
    fetch('/time').then(res => res.json()).then(data => {
        console.log('fetched:' + data);
        setCurrentTime(data.time);
    });
  }, []);

Next, check your ports. It sounds like you may have React/Webpack running on 3001, and the server running on 5000.

Try these:

http://localhost:5000/time

http://localhost:3000/time

http://localhost:3001/time

GAEfan
  • 11,244
  • 2
  • 17
  • 33
  • How can I tell if it is getting hits? The terminal where I called the Flask server is not echoing those prints, if that's what you mean. – Novak Aug 03 '20 at 00:23
  • Yes, that is what I mean. They should print in the terminal. See edit – GAEfan Aug 03 '20 at 00:32
  • This is useful information, that print statements should appear in the Flask terminal window. Second edit: If I understand that, the intent is to reflect log statements into the React console window? In any case, no effect-- no activity in either terminal (React or Flask server) and still incorrect information in the web page. – Novak Aug 03 '20 at 00:46
  • Oh, wait, I see: When I inspect the source and look at the console, I see the first ('fetching') log statement, then errors and not the second one. This is also valuable information, and if the errors do not lead to a solution I will update the question to include them. – Novak Aug 03 '20 at 00:53
  • See edited answer. I think the problem is you are on the wrong port. – GAEfan Aug 03 '20 at 02:30
  • All of those, used in the fetch statement, result in `WebSocket connection to 'ws:///sockjs-node' failed: Error during WebSocket handshake: Unexpected response code: 404` – Novak Aug 03 '20 at 02:54
  • Additionally, an `lsof` command tells me that node is running on 3000, and flask is on 3001, so I know that much is right. – Novak Aug 03 '20 at 02:55