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