middleware(2)

최종윤·2024년 1월 22일
0

JAVASCRIPT

목록 보기
5/6

Router-level middleware

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)
})

Error handling middleware

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!')
})

built-in middleware

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.

third-party middleware

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())
profile
https://github.com/jyzayu

0개의 댓글