---
# System prepended metadata

title: 第九堂：從 express MVC 架構建立 RESTful API
tags: [2025 Node.js 後端工程師培訓營]

---

# 第九堂：從 express MVC 架構建立 RESTful API


1. 錄影
2. [講義簡報](https://whimsical.com/express-7XCkLv6KJUxXD39qoHK9Di)


![Untitled diagram-2025-02-11-072755](https://hackmd.io/_uploads/SkKz3uOKkx.svg)

## express 環境安裝與 router 設計
* 安裝 `express` NPM
``` =JavaScript
const express = require('express');
const app = express();

app.get('/',function(req,res){
    res.status(200).json({
        "name":"洧杰"
    })
})

// 監聽 port
const port = process.env.PORT || 3000;
app.listen(port);
```
## express 語法
* req.query：取得參數
    * [比價網](https://feebee.com.tw/s/iphone/?pl=3300&ph=12000)
    * [TDX 觀光 API](https://tdx.transportdata.tw/api-service/swagger/basic/cd0226cf-6292-4c35-8a0d-b595f0b15352#/)
* req.params：取得動態路由
* req.body(express 產生器)：獲得 post body，就不需要寫原生接 buffer


## 中場休息
* [學習地圖](https://coggle.it/diagram/Yl9rgn_hLg66qEo7/t/node-js-%E7%9B%B4%E6%92%AD%E7%8F%AD%E7%9F%A5%E8%AD%98%E9%BB%9E)、[backend roadmap](https://github.com/goodjack/developer-roadmap-chinese)
* [各週多了一個 CI/CD 資料夾](https://github.com/hexschool/node-training-postgresql/tree/main/week4)

## express 調整

1. 安裝 `cors`、`express` NPM
```
npm install cors express --save
```
## server.js

```jsx
const express = require('express');
const cors = require('cors')
const path = require('path')
const app = express();
const creditPackageRouter = require('./routes/creditPackage')
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')))
app.use('/api/credit-package', creditPackageRouter)

// 監聽 port
const port = process.env.PORT || 3000;
app.listen(port, async () => {
  try {
    console.log(`伺服器運作中. port: ${port}`)
  } catch (error) {
    process.exit(1)
  }
})

```
### router > creditPackage.js
```jsx
const express = require('express')

const router = express.Router()
router.get('/', async (req, res, next) => {

    res.status(200).json({
        status: "success",
        data: "取得資料"
      })
})

router.post('/', async (req, res, next) => {
})

router.delete('/:creditPackageId', async (req, res, next) => {
})

module.exports = router

```


# 在 week4 加上資料庫環境後
## server.js
```jsx
require("dotenv").config()
const express = require('express');
const cors = require('cors')
const path = require('path')
const app = express();
const creditPackageRouter = require('./routes/creditPackage')
const dataSource = require("./db")
app.use(cors())
app.use(express.json())
app.use(express.urlencoded({ extended: false }))
app.use(express.static(path.join(__dirname, 'public')))
app.use('/api/credit-package', creditPackageRouter)

// 監聽 port
const port = process.env.PORT || 3000;
app.listen(port, async () => {
  try {
    await dataSource.initialize()
    console.log('資料庫連線成功')
    console.log(`伺服器運作中. port: ${port}`)
  } catch (error) {
    console.log(`資料庫連線失敗: ${error.message}`)
    process.exit(1)
  }
})
```

## router > creditPackage.js
```javascript
const express = require('express')

const router = express.Router()
// const { dataSource } = require('../db/data-source')
const AppDataSource = require("../db")
router.get('/', async (req, res, next) => {
    const packages = await AppDataSource.getRepository("CreditPackage").find({
        select: ["id", "name", "credit_amount", "price"]
      })
    res.status(200).json({
        status: "success",
        data: packages
      })
})

router.post('/', async (req, res, next) => {
})

router.delete('/:creditPackageId', async (req, res, next) => {
})

module.exports = router
```

## express MVC 架構
```
npm install express --save
```
* 一個方便建立 web 應用程式的框架
* MVC 概念
    * Model：資料層模型
    * Controller：控制器
        * Model 與 View 端的**橋樑**
        * 管理 request、response 
    * View：視圖
* express 產生器：[express generator](https://expressjs.com/zh-tw/starter/generator.html)
* [express cors](https://expressjs.com/en/resources/middleware/cors.html)


## 觀看第五週 GitHub

1. [week5](https://github.com/hexschool/node-training-postgresql/tree/main/week5)