在制作 Flask 服务器时,调用 Flask 后端时出现未找到错误。
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)
这两个都托管在端口 8000 上。
我尝试使用 CORS 并更改 Flask 服务器的端口;然而,这造成的问题比解决的问题还要多。
我还尝试了不同的浏览器(safari 和 duckduckgo)来测试浏览器是否导致了问题。
使用“/get_hello”并设置 CORS 意味着您正在不同的主机上为前端提供服务。像这样的事情你会帮忙的。
templates
文件夹并添加您的 html 文件,并将其命名为 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>
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)