My frontend cannot find my flask backend; how can I fix this?

39 views Asked by At

In making my flask server, I am getting a not found error when calling my flask backend.

index.html:

<!DOCTYPE html>

Button Demo

Click me!

document.getElementById('myButton').addEventListener('click', function() {
    fetch('/get_hello') // Use a relative URL
    .then(response =\> response.text())
    .then(data =\> alert(data))
    .catch(error =\> console.error('Error:', error));
});

app.py:

from flask import Flask
from flask_cors import CORS  # Import CORS from flask_cors

app = Flask`__name__)
CORS(app)  # Enable CORS for your Flask app

@app.route('/')
def index():
    return open('index.html').read()

@app.route('/get_hello')
def get_hello():
    return 'hello world'

if __name__ == '__main__':
    app.run(debug=True, port=8000)

Instead of alerting "hello world" I have been receiving an html response claiming error 404.

Both of these are being hosted on port 8000.

I tried using CORS and changing the port of the flask server; however, that caused more problems than it fixed.

I also tried different browsers (safari and duckduckgo) to test whether or not the browser was causing the issue.

1

There are 1 answers

0
Ssali Jonathan On

Using '/get_hello' and setting up CORS implies you are serving the front-end on a different host. Something like this is what you would help.

  • Create a templates folder and add your html file call it index.html
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Frontend</title>
</head>
<body>
    <button id="myButton">Click Me</button>
</body>
<script >
    document.getElementById('myButton').addEventListener('click', function() {
    fetch('/get_hello') // Use a relative URL
    .then(response => response.text())
    .then(data => alert(data))
    .catch(error => console.error('Error:', error));
});
</script>
</html>
  • Serve the file from Flask
from flask import Flask, render_template


app = Flask(__name__)


@app.route('/')
def index():
    return render_template('index.html')

@app.route('/get_hello')
def get_hello():
    return 'hello world'

if __name__ == '__main__':
    app.run(debug=True, port=8000)