router-level middleware 는 앱-레벨 미들웨어와 동일하게 동작하지만
app object가 아닌 express.Router()에 바인드 됩니다.
router.use() router.METHOD() 를 사용해 라우터레벨 미들웨어를 로드합니다.
next('router')를 호출하여 router instance 에서 제어를 벗어날 수 있습니다.
const express = require('express')
const app = express()
const router = express.Router()
// predicate the router with a check and bail out when needed
router.use((req, res, next) => {
if (!req.headers['x-auth']) return next('router')
next()
})
router.get('/user/:id', (req, res) => {
res.send('hello, user!')
})
// use the router and 401 anything falling through
app.use('/admin', router, (req, res) => {
res.sendStatus(401)
})
need 4 arguments, need next to maintain signature, otherwise fail to handle error (err, req, res, next)
app.use((err, req, res, next) => {
console.error(err.stack)
res.status(500).send('Something broke!')
})
express.json() parses incoming requests with JSON payloads.
app.use(express.json());
app.use('/api/auth', authRoute);
json으로 파싱해서 req.body에 넣은 다음 next route 에 전달하여 실행 ?
This is a built-in middleware function in Express. It parses incoming requests with JSON payloads and is based on body-parser.
Returns middleware that only parses JSON and only looks at requests where the Content-Type header matches the type option. This parser accepts any Unicode encoding of the body and supports automatic inflation of gzip and deflate encodings.
A new body object containing the parsed data is populated on the request object after the middleware (i.e. req.body), or an empty object ({}) if there was no body to parse, the Content-Type was not matched, or an error occurred.
to use third-party middleware, install Nodejs module and load it at application level or router level
example of installing and loading cookie-parser
$ npm install cookie-parser
const express = require('express')
const app = express()
const cookieParser = require('cookie-parser')
// load the cookie-parsing middleware
app.use(cookieParser())