백엔드/express.js

express 문서 - 미들웨어 코드

syleemomo 2024. 4. 15. 15:18
728x90
const express = require('express')
const app = express() 
const port = 3000

const myLogger = function(req, res, next){
    console.log('LOGGED')
    next()
}
const requestTime = function(req, res, next){
    req.requestTime = new Date()
    next()
}

app.use(myLogger)
app.use(requestTime)

app.get('/', (req, res) => {
    let responseText = 'Hello World!'
    responseText += 'Requested at: ' + req.requestTime
    res.send(responseText)
})
app.post('/', (req, res) => {
    res.send('Got a POST request')
})
app.put('/user', (req, res) => {
    res.send('Got a PUT request at /user')
})
app.delete('/user', (req, res) => {
    res.send('Got a DELETE request at /user')
})
app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

 

* 애플리케이션 레벨 미들웨어  

const express = require('express')
const app = express() 
const port = 3000

const myLogger = function(req, res, next){
    console.log('LOGGED')
    next()
}
const requestTime = function(req, res, next){
    req.requestTime = new Date()
    console.log('Time:', new Date().toLocaleTimeString())
    next()
}

app.use(myLogger)
app.use(requestTime)

app.use('/user/:id', function(req, res, next){
    console.log('Request URL: ', req.originalUrl)
    next()
}, function(req, res, next){
    console.log('Request Type: ', req.method)
    next()
})
app.get('/user/:id', function(req, res, next){
    if(req.params.id == 0) next('route')
    else next()
},function(req, res, next){
    res.send('regular')
})
app.get('/user/:id', function(req, res, next){
    res.send('special')
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

 

* 라우터 레벨 미들웨어 

const express = require('express')
const app = express() 
const router = express.Router()
const port = 3000

const myLogger = function(req, res, next){
    console.log('LOGGED')
    next()
}
const requestTime = function(req, res, next){
    req.requestTime = new Date()
    console.log('Time:', new Date().toLocaleTimeString())
    next()
}

router.use(myLogger)
router.use(requestTime)

router.use('/user/:id', function(req, res, next){
    console.log('Request URL: ', req.originalUrl)
    next()
}, function(req, res, next){
    console.log('Request Type: ', req.method)
    next()
})
router.get('/user/:id', function(req, res, next){
    if(req.params.id == 0) next('route')
    else next()
},function(req, res, next){
    res.send('regular')
})
router.get('/user/:id', function(req, res, next){
    res.send('special')
})
app.use('/', router)

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

/sub 의 하위 URL 

const express = require('express')
const app = express() 
const router = express.Router()
const port = 3000

const myLogger = function(req, res, next){
    console.log('LOGGED')
    next()
}
const requestTime = function(req, res, next){
    req.requestTime = new Date()
    console.log('Time:', new Date().toLocaleTimeString())
    next()
}

router.use(myLogger)
router.use(requestTime)

router.use('/user/:id', function(req, res, next){
    console.log('Request URL: ', req.originalUrl)
    next()
}, function(req, res, next){
    console.log('Request Type: ', req.method)
    next()
})
router.get('/user/:id', function(req, res, next){
    if(req.params.id == 0) next('route')
    else next()
},function(req, res, next){
    res.send('regular')
})
router.get('/user/:id', function(req, res, next){
    res.send('special')
})
app.use('/sub', router)

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})

 

* 오류처리 미들웨어

에러 객체를 오류 처리 미들웨어의 첫번째 인자인 err 에 전달한다. 또한, next() 함수로 어떠한 내용을 전달하는 경우('route'라는 문자열 제외), Express는 현재의 요청에 오류가 있는 것으로 간주하며, 오류 처리와 관련되지 않은 나머지 라우팅 및 미들웨어 함수를 건너뛴다.

const express = require('express')
const app = express() 
const router = express.Router()
const port = 3000

const myLogger = function(req, res, next){
    console.log('LOGGED')
    next()
}
const requestTime = function(req, res, next){
    req.requestTime = new Date()
    console.log('Time:', new Date().toLocaleTimeString())
    next()
}

router.use(myLogger)
router.use(requestTime)

router.use('/user/:id', function(req, res, next){
    console.log('Request URL: ', req.originalUrl)
    next()
}, function(req, res, next){
    console.log('Request Type: ', req.method)
    next()
})
router.get('/user/:id', function(req, res, next){
    if(req.params.id == 0) next('route')
    else next()
},function(req, res, next){
    res.send('regular')
})
router.get('/user/:id', function(req, res, next){
    throw new Error("서버에러!")
    res.send('special')
})
app.use('/sub', router)

app.use(function(err, req, res, next){
    console.error(err.stack)
    res.status(500).send('Something broke!')
})

app.listen(port, () => {
    console.log(`Example app listening on port ${port}`)
})
728x90