0
点赞
收藏
分享

微信扫一扫

fastapi&vue 后端数据传到前端(get)

<template>  
  <div class="hello">  
    <h1>{{ msg }}</h1>  
    <button @click="fetchData">按钮</button>  
    <h1>数据来源于后台FastAPI:</h1>
    <p v-if="data">{{ data.long_hello }}</p>
  </div>  
</template>  

<script>  
import axios from 'axios';  

export default {  
  name: 'HelloWorld',  
  props: {  
    msg: String  
  },  
  data() {  
    return {  
      data: null  
    };  
  },  
  methods: {  
    async fetchData() {  
      try {  
        const response = await axios.get('http://localhost:8000/1');  
        this.data = response.data;  
      } catch (error) {  
        console.error("There was an error!", error);  
      }  
    }  
  }  
}  
</script>

fastapi部分

from fastapi import FastAPI  
from fastapi.middleware.cors import CORSMiddleware  

app = FastAPI()  

# 设置跨域策略  
origins = [  
    "http://localhost:8080",  
    "http://your-vue-app.com"  
]  
app.add_middleware(  
    CORSMiddleware,  
    allow_origins=origins,  
    allow_credentials=True,  
    allow_methods=["*"],  
    allow_headers=["*"],  
)  

@app.get("/")  
def read():  
    return {'message': 'hello world!!!'}  
  
@app.get("/1")  
def read_1():  
    return {'long_hello': 'hello world!!!hello world!!!hello world!!!hello world!!!'}

举报

相关推荐

0 条评论