---
# System prepended metadata

title: Advanced Express
tags: [Nodejs]

---

# Advanced Express
###### tags: `Nodejs`

## Nested Routes
一種route的配置方式
例如想在tour這個router中新增一條評論，但評論的功能是被放在review這個router中，而review這個功能又會與tour的id關聯，這時候就會需要nested route
1. 首先到tourRouter.js下新增一個middle ware
```javascript=
router.use('/:tourId/reviews', reviewRouter) // 只要在/tour底下訪問這個路徑就會接到reviewRouter
```
2. 到reviewController修改createReview功能<br>在上面新增兩行判斷以變透過帶入通過protect middleware登入驗證後的user id
```javascript=
// reviewController.js
exports.createReview = catchAsync(async(req, res, next) => {
  // allow nested routes
  if(!req.body.tour) req.body.tour = req.params.tourId
  if(!req.body.user) req.body.user = req.user.id // from protect middleware

  const newReview = await Review.create(req.body)
  res.status(200).json({
    success: 'success',
    data: newReview
  })
})
```
3. 到reviewRouter的router中新增參數使這裡的router能夠存取tourRouter過來的參數
```javascript=
// reviewRouter.js
const router = require('express').Router({ mergeParams: true }) // 增加此參數已接收外層router來的參數
const reviewController = require('../controller/reviewController')
const { protect, restriction } = require('../controller/authController')

router
  .route('/')
  .post(protect, reviewController.createReview)
  .get(protect, reviewController.getReview)

module.exports = router
```