---
tags: Node.js 直播班 - 2022 春季班
---
# 第三週:從 express MVC 架構建立 RESTful API
1. 錄影
2. 鼓勵[第二週週末任務學生](https://hackmd.io/CECy79PTTferGD4j3HHZeA#%E9%80%B1%E6%9C%AB%E4%BB%BB%E5%8B%99%E4%BA%8C%E6%8C%91%E9%81%B8%E5%AF%AB%E6%9C%80%E5%A5%BD%E7%9A%84%E5%89%8D%E5%85%A9%E4%BD%8D%E9%80%81%E6%9B%B8)
3. 點名,[報到]() Code:`JMdbgkWMd1Rx`
4. [Adobe XD 設計稿](https://xd.adobe.com/view/c0763dbe-fc15-42e8-be0b-8956ed03e675-9525/grid)
5. [講義簡報](https://whimsical.com/express-6YpFELUaQsjHnNbCeX8hxD)
## express 環境安裝與 router 設計
``` =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)
* [許願池]()
## express MVC 架構
```
npm install express --save
```
* 一個方便建立 web 應用程式的框架
* MVC 概念
* Model:資料層模型 - MongoDB
* 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)

:::spoiler Mongoose Code
### Mongoose 連線方式
``` =JavaScript
// 資料庫設定開始
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/testPost4')
.then(res=> console.log("連線資料成功"));
```
### Post Model
```=JavaScript
const mongoose = require('mongoose')
const postSchema = new mongoose.Schema(
{
content: {
type: String,
required: [true, 'Content 未填寫']
},
image: {
type:String,
default:""
},
createdAt: {
type: Date,
default: Date.now(),
select: false
},
name: {
type: String,
required: [true, '貼文姓名未填寫']
},
likes: {
type:Number,
default:0
}
}
);
const Post = mongoose.model('Post', postSchema);
module.exports = Post;
```
:::
## 第三週主線任務
* [第三週主線任務網址]()
## 週末任務(不設期限)
請觀看此[技能樹](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),撰寫你想挑戰的許願功能,撰寫文章幫助學生們有研究方向,需附上流程圖: