1. 程式人生 > 程式設計 >FastApi+Vue+LayUI實現前後端分離的示例程式碼

FastApi+Vue+LayUI實現前後端分離的示例程式碼

目錄
  • 前言
  • 專案設計
    • 後端
    • 前端
  • 執行專案
    • Q&A

      前言

      在前面的Api開發中,我們使用FastApi已經可以很好的實現。但是實際使用中,我們通常建議前後端專案分離。今天我們就使用FastApi++LayUI做一個前後端分離的Demo。

      專案設計

      後端

      後端我們採用FastApi在新的test檢視中,定義一個路由,並將其註冊到app中,並且在test檢視中定義一個介面,實現模擬從讀取資料供前端呼叫渲染。
      程式碼

      test.py

      from fastapi import FastAPI,Depends,Header,HTTPException,APIRouter
      from fastapi.param_functions import Body
      from starlette.requests import Request
      from starlette.templating import Jinja2Templates
      from starlette import status
      import uvicorn
      from deta import Deta
      from fastapi.responses import StreamingResponse
      from fastapi.responses import ONResponse
      
      # 例項化路由器
      router = APIRouter()
      templates = Jinja2Templates('templates')
      
      # 注意,檢視這裡使用router來宣告請求方式&URI
      @router.get('/info')
      def user_list(http://www.cppcns.com
      ): # vue的響應資料 items = [ {'id':'1','name':'phyger'},{'id':'2','name':'fly'},{'id':'3','name':'enheng'},] return JSONResponse(content=items) @router.get('/') def welcome(): return "這裡是測試路由" ''' 實際上,這裡的home.html也是需要前端服務去向使用者渲染的, 但是我們為了方便演示,未啟動前端伺服器,直接將前端程式碼寫在了home.html中, 實際上,當用戶請求/check的時候,前端程式碼會去請求/info介面獲取資料, 從而實現前端頁面的資料渲染。 ''' @router.get('/check') def home(request:Request): return templates.TemplateResponse(name='home.html',context={'request':request,})

      前端

      前端我們直接匯入Vue、LayUI、Axios的JS和的CDN資源,在Vue例項的mount階段,使用axios呼叫後端介面拿到資料,使用LayUI的樣式對table元素進行美化。
      程式碼

      <!DOCTYPE html>
      <html lang="en">
      <head>
          <meta charset="UTF-8">
          <meta http-equiv="X-UA-Compatible" content="IE=edge">
          <meta name="viewport" content="wid
      th=device-width,initial-scale=1.0"> <script src="https://unpkg.com/vue@next"></script> <script src="https://unpkg.com/axios/dist/axios.min.js"></script> <!-- 引入 layui.css --> <link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css" rel="external nofollow" /> <!-- 引入 layui.js --> <script src="https://www.layuicdn.com/layui/layui.js" type="text/" charset="utf-8"></script> <title>Home</title> </head> <body> <div id="app"> <table class="layui-table"> <tr v-for="p in infos"> <td>[[ p.id ]]</td> <td>[[ p.name ]]</td> </tr> </table> </div> <table id="test" class="layui-table"></table> <script type="text/script"> const Vapp = Vue.createApp({ data() { return { infos: [{id:1,name:'phyger'}],info: "hello vue..." } },mounted() { this.showinfo(); },FIFwnYhqokmethods: { showinfo(){ axios.get('/test/info') .then(response=>{ this.infos=response.data; console.log(response); console.log(this.infos); }),err=>{ console.log(err); }; },},}) Vapp.config.compilerOptions.delimiters = ['[[',']]'] Vapp.mount('#app') </script> </body> </html>

      執行專案

      啟動 FastApi 後端伺服器,訪問 /test/check 介面。

      FastApi+Vue+LayUI實現前後端分離的示例程式碼

      Q&A

      Q:為什麼在請求/info 介面總會出現一個 Temporary Redirect 重定向呢?

      FastApi+Vue+LayUI實現前後端分離的示例程式碼

      A:原因是因為我們在 FastApi 介面定義的時候,uri 的格式不規範導致,uri 的結尾不需要/,如果你介面增加了/,我們使用瀏覽器訪問 uri,瀏覽器會忽略結尾的/,FastApi 會在內部進行查重定向,將瀏覽器不帶/的請求重定向到我們定義的帶/的檢視函式上。

      到此這篇關於FastApi+Vue+LayUI實現前後端分離的示例程式碼的文章就介紹到這了,更多相關FastApi+Vue+LayUI 前後端分離內容請搜尋我們以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援我們!