I. Basic Principle of Frontend-Backend Interaction¶
In web development, the core of frontend-backend interaction is: the frontend calls the backend API via an HTTP request, the backend processes the request and returns data, and the frontend then renders the data to the page. For example, when a user enters information on the frontend interface and clicks a button, the frontend JavaScript sends an HTTP request to the backend (FastAPI). The backend processes the request parameters and returns a result, which the frontend then displays.
II. Preparation¶
To implement frontend-backend interaction, install the necessary tools and libraries:
- Backend (FastAPI):
Install FastAPI and the ASGI serveruvicorn(used to run the FastAPI application):
pip install fastapi uvicorn
For handling cross-origin requests, CORSMiddleware is built into FastAPI and does not require additional installation.
- Frontend (HTML + JavaScript):
Only an HTML file is needed (no additional dependencies; JavaScript is natively supported by browsers).
III. Backend Interface Practice (FastAPI)¶
First, build a simple backend interface to return data.
Step 1: Create the backend file main.py¶
# main.py
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware # For handling cross-origin requests
app = FastAPI() # Initialize the FastAPI application
# Configure CORS: Allow frontend (use "*" for development, specify domain in production)
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # Allow all frontend origins
allow_credentials=True,
allow_methods=["*"], # Allow all HTTP methods (GET/POST, etc.)
allow_headers=["*"] # Allow all request headers
)
# 1. Simple GET interface: Return JSON data
@app.get("/api/hello")
async def get_hello():
return {"message": "Hello, FastAPI!"} # FastAPI automatically converts dict to JSON
# 2. GET interface with parameters: Return product info by ID
@app.get("/api/items/{item_id}")
async def get_item(item_id: int):
return {
"item_id": item_id,
"name": "Python Tutorial",
"price": 99.99,
"desc": "A practical FastAPI course for beginners"
}
# 3. POST interface: Receive data from frontend and return processing result
@app.post("/api/submit")
async def submit_data(data: dict): # FastAPI automatically parses JSON into a Python dict
return {
"status": "success",
"received": data,
"message": "Data received and processed"
}
Step 2: Start the backend service¶
Run the following command in the terminal to start the FastAPI application (using the uvicorn server):
uvicorn main:app --reload # "main" is the filename, "app" is the FastAPI instance name; --reload enables auto-reload
After successful startup, visit http://localhost:8000/api/hello to see the returned JSON data, indicating the interface works.
IV. Solving Cross-Origin Issues¶
Since the frontend and backend typically run on different ports (e.g., frontend on 5500 and backend on 8000), browsers block cross-origin requests. To fix this, configure CORSMiddleware in FastAPI (done in Step 1).
V. Frontend JavaScript Call Interface (HTML + Fetch)¶
The frontend uses the fetch API (natively supported by browsers) to send HTTP requests, call backend interfaces, and process returned data.
Step 1: Create the frontend HTML file index.html¶
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>FastAPI Frontend Interaction</title>
</head>
<body>
<h1>FastAPI + JavaScript Interaction Example</h1>
<button onclick="fetchGetHello()">Call GET /api/hello</button>
<button onclick="fetchGetItem()">Call GET /api/items/123</button>
<button onclick="fetchPostData()">Call POST /api/submit</button>
<div id="result"></div>
<script>
// 1. Call GET interface: Get simple information
async function fetchGetHello() {
try {
const response = await fetch("http://localhost:8000/api/hello");
if (!response.ok) throw new Error(`Status code: ${response.status}`);
const data = await response.json(); // Parse JSON response
document.getElementById("result").innerHTML = `
<p>Result: ${data.message}</p>
`;
} catch (error) {
document.getElementById("result").innerHTML = `<p>Error: ${error.message}</p>`;
}
}
// 2. Call GET interface: With parameters
async function fetchGetItem() {
try {
const itemId = 123; // Can be replaced with user input
const response = await fetch(`http://localhost:8000/api/items/${itemId}`);
if (!response.ok) throw new Error(`Status code: ${response.status}`);
const data = await response.json();
document.getElementById("result").innerHTML += `
<p>Product Info:</p>
<p>ID: ${data.item_id}</p>
<p>Name: ${data.name}</p>
<p>Price: ${data.price}</p>
`;
} catch (error) {
document.getElementById("result").innerHTML += `<p>Error: ${error.message}</p>`;
}
}
// 3. Call POST interface: Send data to backend
async function fetchPostData() {
try {
const userData = {
name: "Xiaoming",
age: 20,
email: "xiaoming@example.com"
};
const response = await fetch("http://localhost:8000/api/submit", {
method: "POST",
headers: {
"Content-Type": "application/json" // Must specify JSON format
},
body: JSON.stringify(userData) // Convert object to JSON string
});
if (!response.ok) throw new Error(`Status code: ${response.status}`);
const result = await response.json();
document.getElementById("result").innerHTML += `
<p>POST Result:</p>
<p>Status: ${result.status}</p>
<p>Received Data: ${JSON.stringify(result.received)}</p>
`;
} catch (error) {
document.getElementById("result").innerHTML += `<p>Error: ${error.message}</p>`;
}
}
</script>
</body>
</html>
VI. Run and Test¶
- Ensure the backend is running:
uvicorn main:app --reload - Open the frontend
index.htmlfile (directly in the browser, no additional server needed) - Click the buttons to test the three interfaces:
- Call GET /api/hello: Displays “Hello, FastAPI!”
- Call GET /api/items/123: Displays product information
- Call POST /api/submit: Returns received data and status
VII. Key Knowledge Summary¶
- Cross-Origin Issue: Always configure
CORSMiddlewareto allow frontend cross-origin requests (restrictallow_originsto specific domains in production). - HTTP Methods:
-GET: Retrieve data (no request body; parameters in URL).
-POST: Submit data (parameters in request body; setContent-Type: application/json). - JSON Data: Frontend and backend exchange data via JSON;
fetchauto-parsesresponse.json(). - Error Handling: Check HTTP status codes (
response.ok) and network errors to prevent crashes.
VIII. Advanced Extensions¶
- Axios Library: More concise than
fetch, with features like interceptors and request cancellation (install vianpm install axios). - Frontend Frameworks: Use React/Vue to build complex interfaces, with
axiosorfetchfor API calls. - Data Validation: Backend can validate frontend data with Pydantic models to enhance security.
By following these steps, you’ve mastered the core skills of FastAPI backend development and frontend JavaScript interface calls. Explore more complex business scenarios!