Flask API connection issues with React frontend fetch requests

I’m working on a React application that connects to a Flask server as a REST API. Having trouble with fetch requests that keep failing even though the Flask server handles them correctly.

The server logs show successful responses:
127.0.0.1 - - [20/Jul/2021 21:10:35] “GET /api/users HTTP/1.1” 200 -

Postman requests work perfectly. I set up a proxy to HTTP://localhost:5000 in package.json and tried flask_cors but still getting fetch errors. Any ideas what might be wrong?

server.py (route handler)

from . import routes
from flask import jsonify, request

@routes.route('/users', methods=['GET'])
def get_user():
    return jsonify({'message': 'ok'})

routes.py

from flask import Blueprint

routes = Blueprint('api', __name__)

from . import server

app.py

def setup_app():
    from .settings import AppConfig

    application = Flask(__name__)
    application.config.from_object(AppConfig)
    
    from .database import database, Client, Account
    database.init_app(application)
    
    application.register_blueprint(routes, url_prefix='/api')
    return application

React component

export default function UserLogin(props) {
    const [credentials, setCredentials] = useState({})

    function updateField(e) {
        const { name, value } = e.target
        
        if (name === 'username') {
            setCredentials({ ...credentials, username: value })
        } else if (name === 'pass') {
            setCredentials({ ...credentials, pass: value })
        }
    }

    function submitForm(e) {
        fetch('/api/users').then(response => response.json()).catch(err => console.log('failed'))
    }

    return (
        <div>
            <input type="text" name="username" onChange={updateField} />
            <input type="password" name="pass" onChange={updateField} />
            <button onClick={submitForm}>Login</button>
        </div>
    )
}

The circular import is definitely an issue, but import order matters too. You need to define your routes before registering the blueprint in app.py. Right now when you import routes in app.py, the Blueprint gets created but the route handlers aren’t attached yet—server.py hasn’t defined the routes at that point. I ran into this same problem. Fix it by making sure you define routes before registering the blueprint, or just define the routes directly in routes.py to skip the circular dependency altogether.

you’ve got a circular import - server.py and routes.py are importing each other. move the route decorator directly into routes.py instead of importing server from routes.

Interesting setup! Are you getting any error messages in your browser console when the fetch fails? And is your Flask app definitely running on port 5000 when you test this?