app.py
from flask import Flask, jsonify, render_template
app = Flask(__name__)
# 定義首頁路由,渲染 React 的入口 HTML 文件
@app.route('/')
def index():
return render_template('index.html')
# 定義一個 API 路由,返回 JSON 數據
@app.route('/api/data')
def get_data():
data = {"message": "Hello from Flask!"}
return jsonify(data)
# 啟動 Flask 應用
if __name__ == '__main__':
app.run(debug=True)
index.html
<!DOCTYPE html>
<html lang="zh-Hant">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>第十八天 - React 與 Flask 整合</title>
</head>
<body>
<div id="root"></div>
<script src="https://unpkg.com/react@17/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.development.js"></script>
<script src="https://unpkg.com/babel-standalone@6/babel.min.js"></script>
<script type="text/babel">
function App() {
const [message, setMessage] = React.useState('');
React.useEffect(() => {
fetch('/api/data')
.then(response => response.json())
.then(data => setMessage(data.message));
}, []);
return (
<div>
<h1>第十八天的 React 與 Flask 整合示範</h1>
<p>{message}</p>
</div>
);
}
ReactDOM.render(<App />, document.getElementById('root'));
</script>
</body>
</html>