vue3+fastAPI最简单例子
我想学习vue3和fastAPI,我想做一个最简单的项目练习一下。 网页中只有一个输入框和按钮。按钮实现的功能是,把输入框中的数值加2.这个加法由python语言实现。
0、项目结构:
my_project/
│
├── frontend/ # Vue 3前端项目
│ ├── src/
│ │ ├── App.vue
│ │ ├── main.js
│ │ └── components/
│ │ └── HelloWorld.vue
│ ├── public/
│ │ └── index.html
│ └── package.json
│
└── backend/ # FastAPI后端项目
├── main.py
└── requirements.txt
一、后端(FastAPI)
1、安装FastAPI和Uvicorn(用于运行FastAPI应用):
pip install fastapi uvicorn
2、在backend/main.py
中编写以下代码:
from fastapi import FastAPI, HTTPException
from fastapi.middleware.cors import CORSMiddleware
from pydantic import BaseModel
app = FastAPI()
# 添加 CORS 中间件
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 允许所有来源,或指定特定的来源
allow_credentials=True,
allow_methods=["*"], # 允许所有方法
allow_headers=["*"], # 允许所有头部
)
class Item(BaseModel):
number: int
@app.post("/add_two/")
async def add_two(item: Item):
if item.number is None:
raise HTTPException(status_code=400, detail="Number is required")
return {"result": item.number + 2}
3、运行后端服务:
uvicorn backend.main:app --reload
二、前端(Vue 3)
1、安装Axios(用于发送HTTP请求):
npm install axios
2、代码
<template>
<div id="app">
<input v-model="number" type="number" placeholder="Enter a number" />
<button @click="addTwo">Add Two</button>
<p>Result: {{ result }}</p>
</div>
</template>
<script>
import axios from 'axios';
export default {
name: 'App',
data() {
return {
number: 0,
result: 0,
};
},
methods: {
async addTwo() {
console.log("addTwo method called");
try {
console.log("Current number:", this.number); // 调试信息
const response = await axios.post('http://127.0.0.1:8000/add_two/', { number: this.number });
this.result = response.data.result;
console.log("Result:", this.result); // 调试信息
} catch (error) {
console.error(error);
}
},
},
};
</script>
<style>
#app {
font-family: Avenir, Helvetica, Arial, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
text-align: center;
color: #2c3e50;
margin-top: 60px;
}
</style>
3、运行前端项目:
npm run serve