next 활용법

김무연·2023년 12월 14일

Backend

목록 보기
36/49

편리한 json

원래 http에서는 아래와 같았던 것을

res.writeHead(200, { 'content-type' : 'application/json' });
res.end(JSON.stringify({ hello : "mumu}));

express 에서는 아래와 같이 편리하게 쓸 수 있다.

res.json({hello:'mumu'});

next를 활용한 에러 처리

app.use((req, res, next) => { // 에러 처리
  console.log("모든 요청에 실행하고 싶어요")
  next()
}, (req, res, next) => {
  try {
    console.log(asd)
  } catch(error) {
    next(error)
  }
})

try, catch 구문으로 error를 잡아서 , next에 인자로 넘겨주 면, 미들웨어 next가 아닌, 에러처리 미들웨어로 넘어가지게 됨

next의 특별한 기능

next의 인자에 'route'를 넣어주면 다음 미들웨어가 아닌 다음 라우터가 실행이 됨

app.get('/', (req, res, next) => {
  res.send('hello express');
  if (ture) {
    next('route')
  } else {
    next();
  }
}, (req, res) => {
  console.log("실행되나요?")
});

app.get('/', (req, res) => {
  res.sendFile(path.join(__dirname, 'index.html'));
  console.log("렌더링 됬어요")
});

위 처럼 next('route')가 있으면 다음 라우터 밑의 get이 실행이 되고 아니면 밑의 미들웨어가 실행, if 문처럼 조건 넣어서 코드의 중복을 줄일 때 사용됨

profile
Notion에 정리된 공부한 글을 옮겨오는 중입니다... (진행중)

0개의 댓글