Flask后端调用出现404错误,前端无法找到后端如何解决?
解决Flask后端404错误的步骤
1. 修复Flask初始化的语法错误
你的app.py存在语法错误,直接导致Flask应用无法正确初始化,路由未被正常注册:
错误代码:
app = Flask`__name__)
修正为:
app = Flask(__name__)
2. 修复前端HTML结构与元素ID
你提供的index.html缺少完整HTML结构,且按钮未指定id="myButton",导致JS无法找到目标元素绑定点击事件。正确的index.html写法如下:
<!DOCTYPE html> <html> <head> <title>Button Demo</title> </head> <body> <button id="myButton">Click me!</button> <script> document.getElementById('myButton').addEventListener('click', function() { fetch('/get_hello') .then(response => response.text()) .then(data => alert(data)) .catch(error => console.error('Error:', error)); }); </script> </body> </html>
3. 规范Flask返回HTML的方式
使用Flask自带的render_template更可靠,需要先在app.py同目录下创建templates文件夹,将index.html放入其中,再修改app.py:
from flask import Flask, render_template from flask_cors import CORS app = Flask(__name__) CORS(app) @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)
验证步骤
- 启动Flask服务器,直接访问
http://localhost:8000/get_hello,确认页面显示hello world,说明路由已正常注册。 - 访问
http://localhost:8000,点击按钮即可弹出hello world提示框。
内容的提问来源于stack exchange,提问作者SC0TT
相关产品推荐
相关产品推荐

