Minwook’s portfolio

Express에서 next()의 기능분석 및 에러처리방법 본문

Today I Learned

Express에서 next()의 기능분석 및 에러처리방법

yiminwook 2022. 10. 17. 18:10

 

Express nodeJS의 Web Framework이다.

Express의 주요기능은 middle ware와 route가 있다.

그중 midde ware에 대해서 자세히 분석하고자 한다.

 

우선 Middle ware란? 

req, res, 그리고 next 함수에 액세스 권한을 갖는 함수이다.

즉, Express내에서 우리가 작성하는 대부분의 코드는 미들웨어라고도 볼 수 있다.

 

app.use(function (req, res, next) {
  console.log('Time:', Date.now());
  next();
});

https://expressjs.com/ko/guide/using-middleware.html

위 코드는 Express 공식문서에서 middle ware의 예제이다.

 


 

우리는 NodeJS에서 req, res를 많이 접해보았을 것이다.

그런데 예제에서 인자로 전달되는 next는 무엇인가?

해당 글에서는 middle ware에서 next()의 역할에 대해서 자세히 알아보도록 하겠다.

const express = require('express');
const app = express();
const port = 8080;

//GET http://localhost:8080/
app.get('/', (req, res, next) => {
  console.log("1")
  next()
})

app.get("/", (req, res, next) => {
  console.log("2")
})

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

express를 설치하고 위코드를 작성후 서버를 작동시킨 뒤 http://localhost:8080/ 으로 GET요청을 보내면 

 

//console.log()
Example app listening on port 8080
1
2

위와 같이 콘솔로그가 Terminal에 출력된다.

이를 보아 알수있는 사실은 next()가 다음 함수, route를 실행시킨다는 사실이다.

 


 

next()에 "route"를 인자로 전달하면 이전과 살짝 다르게 활용 할수있다.

{}안에 컴마(,)를 넣으면 여러개의 함수를 넣을 수 있다.

이를 이용해 방금 코드를 수정한다.

//GET http://localhost:8080/
app.get('/', (req, res, next) => {
  console.log("1")
  next("route"),
  console.log("2")
})

app.get("/", (req, res, next) => {
  console.log("3"),
  console.log("4")
})
//console.log()
Example app listening on port 8080
1
3
4
2

콘솔로그를 통해 출력되는 결과값을 보면

1이후에 route가 넘어갔다가 3,4를 실행시킨 뒤에

돌아와서 2가 실행되는 것을 알 수 있다.

 

즉, next()함수에 "route"라는 string을 인자로 전달하면

다음 함수를 실행시키는 것이 아닌 다음 route를 실행 시킬 수 있다.

 


 

next함수에 인자를 "route"이외의 값을 넣으면 특별한 기능을 한다.

//공식문서 예제
function errorHandler (err, req, res, next) {
  if (res.headersSent) {
    return next(err)
  }
  res.status(500)
  res.render('error', { error: err })
}

https://expressjs.com/en/guide/error-handling.html

Express 공식문서에서 error handling 예제는 위와 같다.

 

next()에 인자를 "route"이외의 값을 전달하면 err라는 인자를 가지고 있는 함수에 전달된다.

 

즉, next()에 인자를 전달하는 것으로 error handling을 할 수 있다.

이를 활용하여 코드를 작성해보겠다.

 

//GET http://localhost:8080/
app.get('/', (req, res, next) => {
  try{
    console.log("1");
  } catch (err) {
  next(err); 
  }
  console.log("2")
})

app.use((err, req, res, next) => {
  console.log(err);
  return res.status(200).send("Error!");
})

위 코드와 같은 방식으로 활용 할 수 있다.

 

+

 

추가적으로 Express의 middle ware는 순차적으로 실행된다 

이점을 활용하여 또 다른 방식으로 error handling 구현할 수 있다.

 

//GET http://localhost:8080/
app.get('/', (req, res, next) => {
  try{
    console.log("1");
  } catch (err) {
  next(err) 
  }
  console.log("2");
})

app.use((err, req, res, next) => {
  console.log(err);
  return res.status(200).send("Error!");
})

//GET http://localhost:8080/invalidPath
app.use((req, res, next) => {
  return res.status(404).send("Not found!"); //올바르지않은 url path로 접근시 "Not found"출력
})

위와 같이 올바르지 않은 path로 접근했을때 마지막에 있는 Middle ware를 실행시키는 것으로 에러를 보낼 수 있다.

 


 

참고

https://www.youtube.com/watch?v=2UftvRY-J9A&list=PLuHgQVnccGMAGOQu8CBDO9hn-FXFmm4Wp&index=16

'Today I Learned' 카테고리의 다른 글

Hashtable 정리  (0) 2022.12.28
배열(Array) 정리  (0) 2022.12.26
시간복잡도, Big O 표기법  (1) 2022.12.26
node version 관리 및 npm install option  (0) 2022.08.31
HTTP header CORS 설정  (1) 2022.08.27
Comments