Backend/Node.js

[Node][Express] all & use 메소드

Rayi 2024. 8. 16. 20:07

 Express는 각 http 메소드를 통해 특정 엔드포인트에 접근할 때 미들웨어 함수를 호출할 수 있습니다.

여기에 더해 express는 다른 메소드 함수도 제공하고 있습니다.

all( )

all 함수는 모든 종류의 http 메소드에 해당합니다.

따라서 POST, GET 등의 메소드 종류에 관계 없이 미들웨어를 호출합니다.

const app = express()

// all은 모든 메소드에서 호출됩니다.
app.all('/endpoint', (req, res, next) => {
    console.log('all method called')
    next()
})

// GET 메소드에서만 호출됩니다.
app.get('/endpoint', (req, res, next) => {
    console.log('GET method called')
    res.json({ value: 'get'})
    next()
})

app.listen(3000, () => {
    console.log('Server is listening on port 3000');
});

위 코드를 기반으로 엔드포인트 /endpoint로 GET 메소드를 호출한다면, app.all( )의 미들웨어와 app.get( )의 미들웨어 총 두 개의 미들웨어 함수가 호출됩니다.

// app.all()과 app.get() 총 두 개의 미들웨어를 호출합니다.
$ GET https://localhost:3000/endpoint

all method called
GET method called

use( )

use 함수 또한 http 메소드와 관계 없이 지정한 미들웨어를 호출하게 합니다.

all과 다른 점은 엔드포인트의 경로도 특정할 수 있다는 것입니다.

all의 경우 모든 메소드에 호출되지만, 지정한 엔드포인트로 향하지 않는 메소드에는 호출되지 않습니다.

use는 지정한 엔트포인트를 지나는(= 하위에 있는) 엔드포인트들에도 호출됩니다.

const app = express()

// /endpoint를 거치는 모든 엔드포인트로 향하는 모든 메소드에서 호출됩니다.
app.use('/endpoint', (req, res, next) => {
    console.log('use method called')
    next()
})

// /endpoint/field1로 향하는 모든 메소드에서 호출됩니다.
app.all('/endpoint/field1', (req, res, next) => {
    console.log('all method called')
    next()
})

// /endpoint/field2로 향하는 GET 메소드에서만 호출됩니다.
app.get('/endpoint/field2', (req, res, next) => {
    console.log('GET method called')
    res.json({ value: 'get'})
    next()
})

app.listen(3000, () => {
  console.log('Server is listening on port 3000');
});

위 코드를 기반으로 GET https://localhost:3000/endpoint/field2 를 요청하면 all의 미들웨어는 호출되지 않습니다.

하지만 use의 /endpoint를 지나기 때문에 use의 미들웨어는 호출됩니다.

// app.use()와 app.get() 총 두 개의 미들웨어를 호출합니다.
$ GET https://localhost:3000/endpoint/field2

use method called
GET method called

use( )의 엔드포인트는 생략 가능합니다. 이때, use는 모든 엔드포인트에 대해 호출됩니다.

app.use('/endpoint', (req, res, next) => {
    console.log('use method called')
    next()
})
728x90