Flask渲染模板后HTML链接返回404 Not Found错误求助
解决Flask页面跳转404问题
你的问题出在两个核心点:未给contact页面配置Flask路由,以及HTML链接路径不符合Flask的工作逻辑。以下是具体修复步骤:
1. 为contact页面添加路由
修改app.py,新增处理contact页面的路由函数,让Flask能够识别并响应该页面的请求:
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return render_template('index.html') # 新增contact页面的路由 @app.route('/contact') def contact(): return render_template('contact.html') if __name__ == "__main__": app.run(debug=True)
2. 修正HTML中的链接路径
Flask的templates目录是后端专属的模板存储目录,不能直接通过URL访问其中的文件。你需要将链接指向刚配置的路由路径,而非模板文件的物理路径。修改index.html中的链接代码:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta name="description" content="Don's first website :D"> <title>Don's website</title> <style> </style> </head> <body> <a href="/contact">other website</a> </body> </html>
完成修改后重启Flask服务,点击链接即可正常跳转到contact页面。
内容的提问来源于stack exchange,提问作者Beginnercoder
相关产品推荐
相关产品推荐

