在routes資料夾中,建立product.ts:
1.匯入模組:
import express from 'express';
import { ControllerContext } from '@/manager/controllerManager';
2.函數定義:
export const mountProductRouter =
({ controllerCtx }: { controllerCtx: ControllerContext }) => {}
controllerCtx
符合 ControllerContext
介面。3.設置路由:
let router = express.Router();
router.get('/list', controllerCtx.productController.findAll)
return router;
/list
只是用來表示產品清單的 URL。可以根據需求改成其他名字,例如 /products
、/all-products
或者任何符合你應用程式設計的名稱。private routerSetup() {
this.app.use('/products',
mountProductRouter({ controllerCtx: this.controllerCtx })
);//將mountProductRouter的router傳出來
}
<script src="/javascripts/index.js"></script>
index.js
檔案中編寫產品資料庫路由,處理 API 請求:index.js
1.serverDomain:
用來存儲伺服器地址的變數,目的是定義伺服器的域名和端口號,方便在應用程式中統一使用。
const serverDomain = 'http://localhost:30000';
2.導入 Vue:
使用 const { createApp } = Vue;
是因為 Vue 3 將功能分成多個模組,符合現代 JavaScript 的模組化標準。
const { createApp } = Vue;
3.創建應用程式:
createApp({
data() {
return {
products: []
}
},
async mounted() {
this.products = await fetch(`${serverDomain}/products/list`)
.then((res) => res.json());
console.log("~ file:index.js ~line 14 ~ mounted ~ this.products", this.products);
}
}).mount("#app")
createApp({ ... })
:使用 createApp
函數創建一個新的 Vue 應用實例,並傳入一個配置對象。data() { return { products: [] } }
:在配置對象中定義一個 data
函數,返回應用實例的初始數據。這裡定義了一個 products
陣列,初始值為空。this.products = await fetch()
:使用 fetch()
函數發起非同步請求來獲取數據,並將返回的數據賦值給 products
屬性。fetch
函數發起一個 GET 請求,請求的 URL 是 ${serverDomain}/products/list
。${serverDomain}
是一個變數,用來動態替換為實際的伺服器域名。(res) => res.json()
是一個箭頭函數,用來將響應對象(res)轉換為 JSON 格式的數據。this.products = ...
:將解析後的 JSON 數據賦值給 this.products 屬性。console.log("~ file:index.js ~line 14 ~ mounted ~ this.products", this.products);
:這行代碼用來列印 this.products 的內容到瀏覽器的控制台,以便開發者可以查看和調整。index.js
檔案中使用 Vue:index.js
檔案中修改body: