---
tags: Node.js 直播班 - 2023 春季班
---
# 🏅 Day 13 - Express 應用程式產生器(Express generater)、在 routes 設計路由
express 應用程式產生器可以快速產生一個應用程式架構
安裝步驟
- 先開好一個新專案
- 執行 `npm install express-generator -g`
- 接著切換到專案路徑下,執行 `express --no-view`
可參考[文件](https://expressjs.com/zh-tw/starter/generator.html)查看指令選項
注意:這裡需要選擇 `no view`,因最終作業最後設計出的 API 只需要回傳 JSON 資料,不會使用到 view 模板引擎
:::spoiler 指令選項
```
$ express -h
Usage: express [options][dir]
Options:
-h, --help output usage information
--version output the version number
-e, --ejs add ejs engine support
--hbs add handlebars engine support
--pug add pug engine support
-H, --hogan add hogan.js engine support
--no-view generate without view engine
-v, --view <engine> add view <engine> support (ejs|hbs|hjs|jade|pug|twig|vash) (defaults to jade)
-c, --css <engine> add stylesheet <engine> support (less|stylus|compass|sass) (defaults to plain css)
--git add .gitignore
-f, --force force on non-empty directory
```
:::
執行成功後應該會出現以下結構
:::spoiler 資料夾結構
```
├── app.js
├── bin
│ └── www
├── package.json
├── public
│ ├── images
│ ├── javascripts
│ ├── stylesheets
│ └── style.css
└── index.html
└── routes
├── index.js
└── users.js
```
:::
此結構已將 routes 的部分拆成獨立模組,並在 app.js 引入
在 routes 的 index.js 或 users.js,會使用 `const router = express.Router()`
並使用 `router` 來設定路由
```javascript
router.get('/', function(req, res, next) {
res.send('respond with a resource');
});
```
需注意在 app.js 引入使用時,就會自動帶入 `/users`,因此 users.js 中 path 可直接從 `/users` 之後開始(`router.get('/', ...)` 就會是 `/users`)
```
const usersRouter = require('./routes/users');
app.use('/users', usersRouter);
```
第一次啟用伺服器時需執行 `npm install` 安裝相關套件,並執行 `npm start`
若想使用 nodemon 運行也可自行在 package.json 加上指令,並使用 `npm run start:dev` 運行
```json
"scripts": {
"start": "node ./bin/www",
"start:dev": "nodemon ./bin/www"
},
```
### 參考資源
- [Express 應用程式產生器](https://expressjs.com/zh-tw/starter/generator.html)
- [Express - API](http://expressjs.com/zh-tw/api.html#express.router)
- 課程影音「Router 進階設定」到「express-generator(下)」
## 題目(將答案寫在 HackMD 並提交至回報區)
此[專案](https://github.com/dogwantfly/express-user)為使用 express generater 產生的結構,請嘗試在此 routes 資料夾的 users.js,設計新增及修改個人資料的路由(搭配動態路由),在註解處填上答案(可使用 POSTMAN 測試是否可正確運作),完成後將 users.js 的程式碼貼到 HackMD 並提交至回報區
## 回報流程
將答案連結貼至底下回報就算完成了喔!
解答位置請參考下圖(需打開程式碼的部分觀看)

<!-- 解答:
users.js 範例參考(可自行優化程式碼)
```javascript
const express = require('express');
const router = express.Router();
const User = require('../models/users');
/* GET users listing. */
router.get('/', async (req, res, next) => {
const allUser = await User.find();
res.status(200).json({
"status": 'success',
"data": allUser
});
});
router.delete('/', async (req, res, next) => {
await User.deleteMany({});
res.status(200).json({
"status": 'success',
"data": ''
});
});
router.post('/', async (req, res, next) => {
try{
const data = req.body;
let { nickName, gender, avatar} = data;
if(!nickName||!gender){
// 回傳失敗
res.status(400).json({
"status": 'false',
"message": "使用者資料未填寫完整"
});
} else {
// 新增至 User model
const newUser = await User.create(
{
nickName,
gender,
avatar
}
);
res.status(200).json({
"status": 'success',
"data": newUser
});
}
} catch (error) {
// 回傳失敗
res.status(400).json({
"status": 'false',
"message": error.message
});
}
});
// 修改
router.patch('/:id', async (req, res, next) => {
try{
// 取得 id
const id = req.params.id;
const data = req.body;
let { nickName, gender, avatar } = data;
if(!nickName||!gender){
// 回傳失敗 "使用者資料未填寫完整"
res.status(400).json({
"status": 'false',
"message": "使用者資料未填寫完整"
});
} else {
const editContent = {
nickName,
gender
}
// 找出此筆 id 並編輯資料
// const editUser =
const editUser = await User.findByIdAndUpdate(id, editContent, { new: true });
if (editUser) {
res.status(200).json({
"status": 'success',
"data": editUser
});
} else {
res.status(400).json({
"status": 'false',
"message": "id 不存在"
});
}
}
} catch (error) {
// 回傳失敗
res.status(400).json({
"status": 'false',
"message": error.message
});
}
});
module.exports = router;
```
-->
回報區
---
| 報數 | 組別/Discord 名字 | Codepen/HackMD/其他回饋 |
|:----:|:------------------:|:--------------------------------------------------------------------------------------------------------------------------------------------:|
| 1 | 北 10 組 / Benson | [Github Benson - Day 13](https://github.com/ioveasdkre/HexschoolOperation/tree/main/NodejsEnterpriseClass/day40-tasks/day13/routes/users.js) |
| 2 | 北 1 組 / PittWu | [Blog Post - Day 13](https://pitt-wu-blog.vercel.app/docs/day13-express-generator) |
| 3 | 中 4 組 / jimkk159 | [HackMD - Day 13](https://hackmd.io/6HUYVNYdTFuda2OKFCVZcg) |
| 4 | 北 12 組 / Sam Lin | [GitHub - Day 13](https://github.com/samlin1122/hex-school/blob/main/daily-challenges/day13.js)|
| 5 | 北 5 組 / 圈圈 | [HackMD - Day 13](https://hackmd.io/@j6ccRYgTTEiVcfMfmAELcw/HJQkS4lb2)|
| 6 | 中 3 組 / Wendy | [Notion - Day 13](https://jewel-cellar-80e.notion.site/Day-13-Express-Express-generater-routes-1c8a5b1f7c01444a9d976bfbf822efbf)|
| 7 | 北 13 組 / Louisa | [GitHub - Day 13](https://github.com/louisa0416/NodejsEnterpriseClass/tree/master/daily-task/day13) |
| 8 | 北 13 組 / sasha | [HackMD - Day 13](https://hackmd.io/@sashaye/Sy3G9Xdbn)|
| 9 | 北 16 組 / 啊培培 | [GitHub - Day 13](https://github.com/LABIBI-LG/Courses/blob/main/hexschool/nodeJS/Live_Course/Daily_Tasks/day13/routes/users.js)|