fastapi前后端对接
时间: 2025-02-16 14:11:33 浏览: 47
### 使用 FastAPI 实现前后端对接
为了实现 FastAPI 与前端的对接,通常会采用前后端分离的方式。在这种架构下,FastAPI 负责处理业务逻辑并提供 API 接口供前端调用;而前端则负责展示数据并与用户交互。
#### 启用 CORS 支持
由于浏览器的安全策略,默认情况下不允许跨域请求。因此,在 FastAPI 中需要启用 CORS (Cross-Origin Resource Sharing),以便允许来自不同源的 HTTP 请求[^2]:
```python
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
app = FastAPI()
origins = ["http://localhost", "http://localhost:8080"]
app.add_middleware(
CORSMiddleware,
allow_origins=origins,
allow_credentials=True,
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/")
async def read_root():
return {"message": "Hello World"}
```
这段代码配置了 `CORSMiddleware` 来接受特定域名下的请求,并开放所有的HTTP方法和头部信息访问权限。
#### 创建 RESTful API 接口
定义一些简单的 CRUD 操作作为示例来说明如何创建RESTful风格的API接口。这里假设有一个名为 Item 的资源类[^1]:
```python
from pydantic import BaseModel
from typing import List, Optional
class Item(BaseModel):
id: int
name: str
description: Optional[str] = None
price: float
items_db = []
@app.post("/items/", response_model=Item)
def create_item(item: Item):
items_db.append(item.dict())
return item
@app.get("/items/{item_id}", response_model=Item)
def get_item(item_id: int):
for i in items_db:
if i['id'] == item_id:
return i
raise HTTPException(status_code=404, detail="Item not found")
@app.put("/items/{item_id}", response_model=Item)
def update_item(item_id: int, updated_item: Item):
global items_db
new_items_db = []
for i in items_db:
if i['id'] != item_id:
new_items_db.append(i)
else:
new_items_db.append(updated_item.dict())
items_db = new_items_db
return updated_item
@app.delete("/items/{item_id}")
def delete_item(item_id: int):
global items_db
items_db = [i for i in items_db if i['id'] != item_id]
return {"detail": f"Deleted item with ID {item_id}"}
```
上述代码展示了四个基本操作:新增(`POST`)、查询(`GET`)、更新(`PUT`) 和删除 (`DELETE`) 数据项的功能。
#### 前端调用方式
对于 Vue.js 或其他 JavaScript 框架来说,可以利用 Fetch API 或 Axios 发送异步请求给后端服务器。下面是一个基于Vue3组件的例子,它实现了向 `/items/` 地址发送 POST 请求以保存新物品的信息:
```javascript
<template>
<div class="container">
<!-- 表单 -->
<form @submit.prevent="handleSubmit()">
<label>名称:</label><input v-model="name"/>
<br/>
<label>描述:</label><textarea v-model="description"></textarea>
<br/>
<label>价格:</label><input type="number" step="any" v-model="price"/>
<button type="submit">提交</button>
</form>
{{ message }}
</div>
</template>
<script setup lang="ts">
import axios from 'axios';
import { ref } from 'vue';
const name = ref('');
const description = ref('');
const price = ref<number | null>(null);
let message = '';
function handleSubmit() {
const newItem = { name: name.value, description: description.value || undefined, price: parseFloat(price.value!) };
axios({
method: 'post',
url: '/items/',
data: newItem
}).then((response) => {
console.log(response.data); // 输出返回的数据对象
message = JSON.stringify(response.data);
}).catch(error => {
console.error('There was an error!', error);
});
}
</script>
```
此模板中的表单用于收集用户的输入并通过 `handleSubmit()` 方法触发 AJAX 提交动作至指定 URL 上面定义好的路由路径上。
阅读全文
相关推荐



















