본문 바로가기
WEB/Nodejs-express

[Nodejs-express] 미들웨어 만들기

by Ellen571 2020. 8. 9.

[생활코딩] Express 미들웨어 만들기

 

 

공통적으로 사용되는 로직

 

fs.readdir('./data', function(error, filelist){
    ...
    var list = template.list(filelist);
	...
});

 

공통적인 부분 미들웨어로 만들기

 

app.use(function(req, res, next){
// 첫번째 매개변수로 req, 두번째 매개변수로 res, 세번째 매개변수로 next를 받게 약속됨 
	fs.readdir('./data', function(error, filelist){
    	// data 디렉토리에 있는 파일목록을 가져와 filelist에 넣고 function 호출
    
                req.list = filelist; // filelist를 req객체의 list값으로 담음
                next(); // 이 미들웨어 다음에 있는 미들웨어 실행
        }); 
});

 

 

만든 미들웨어 사용하기

 

app.get('/', function(req, res){
  console.log(req.list); // readdir미들웨어가 실행되었기에 req객체에는 list가 들어있음

  var title = 'Welcome';
  var description = 'Hello, Node.js';
  var list = template.list(req.list); // filelist를 req.list로 변경
  var html = template.HTML(title, list,
    `<h2>${title}</h2>${description}`,
    `<a href="/create">create</a>`
  );
  res.send(html);
});

 

BUT

 

list가 필요하지 않은 곳에서도 req 요청이 있을 때마다 list를 읽어오고 있음

 

 

미들웨어가 필요한 곳만 사용하기

 

app.get('*', function(req, res, next){
// get으로 받는 모든 요청만 적용

  fs.readdir('./data', function(error, filelist){
      req.list = filelist;
      next();
  });
});

 

post방식일 때는 req.list를 읽어오지 않음

반응형