ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 노드 next 활용법
    노드 2023. 4. 17. 18:22

    res.json

    http 모듈로 데이터를 json으로 쓰기를 간단히 하면 다음과 같다

    res.writeHead(200, { 'Content-Type' : 'application/json' });
    res. end(JSON.stringify({ hello: 'me'}));

    이 부분이 express에서 굉장히 간단하게 변한다.

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

     

    *기본 http의 모듈의 메서드들은 거의 사용하지 않게 된다. 

     

    next를 사용해서 에러 처리

    의도적으로 throw 를 통해서 에러를 발생시킬 수 있지만 실무에서 에러는 보통 catch 문을 통해 접근한다.

    //app.js
    const express = require('express');
    const path = require('path');
    
    const app = express();
    app.set('port', process.env.PORT || 3000);
    
    app.use((req, res, next) => {
      console.log('모든 요청에 실행');
      next();
    }, (req, res, next) => {
      try {
        throw new error('에러1111');
      } catch (error) {
        next(error);
      }
    })
    
    app.get('/', (req, res) => {
      res.sendFile(path.join(__dirname, '/index.html'));
    });
    
    app.post('/', (req, res) => {
      res.send('hello express!');
    });
     
    app.get('/about', (req, res) => {
      res.send('hello express');
    });
    
    app.use((err, req, res, next) => {
      console.error(err);
      res.send('에러 발생');
    })
    
    app.listen(app.get('port'), () => {
      console.log(app.get('port'), '번 포트에서 대기 중');
    });

    try catch 블럭에서 에러가 발생했다. 그리고 에러가 발생하면 catch 부분이 실행된다. 

     

    그럼 여기서 next는 다음 미들웨어로 넘어가는 것이 아닌가? 라고 생각할 수 있다.

    다음 미들웨어로 넘어가는 건 next의 인자가 없을 때이다.

     

    next(error) 하면 다음 미들웨어로 넘어가는 것이 아니라 에러처리 미들웨어로 넘어간다.

     

    실행하면 다음과 같다

     

    *next('route');

    해당 라우트의 다음 미들웨어로 넘어가는 것이 아니라 다른 라우터로 넘어간다.

    app.get('/', (req, res, next) => {
      res.sendFile(path.join(__dirname, 'index.html'));
      next('route');
    }, (req, res) => {
      console.log('실행11');
    });
    
    app.get('/', (req, res) => {
      console.log('실행22');
    });

    이런 코드가 있다고 하면 실행 11이 출력되는 것이 아니라 실행 22가 출력된다. 

    '노드' 카테고리의 다른 글

    노드 관계 쿼리  (0) 2023.04.18
    노드 테이블 관계 이해하기  (0) 2023.04.18
    노드 미들웨어 특성 이해하기  (0) 2023.04.17
    노드 미들웨어 사용하기  (0) 2023.04.17
    노드 express로 html 서빙하기  (0) 2023.04.17
Designed by Tistory.