Middleware
- A tool that helps develop Node.js based applications by automatically restarting the node application when file changes in the directory are detected.
- 요청과 응답의 중간에 위치하며, 그 다음의 미들웨어 함수에 대한 액세스 권한을 갖는 함수
1) morgan
- morgan 연결 후 localhost에 재접속 해보면 기존 로그 외에 추가적인 로그 확인 가능
- app.use(morgan('dev'));
- dev, combined, common, short, tiny 등
2) static
- 정적인 파일들을 제공하는 라우터 역할
- 기본적으로 제공됨으로 따로 설치할 필요 없음
- app.use('/', express.static(path.join(__dirname, 'public')));
- public/stylesheets/style.css --> http://localhost:3000/stylesheets/style.css로 접근 가능
- 서버의 폴더 경로와 요청 경로가 다르므로 외부인이 서버의 구조를 쉽게 파악할 수 없음 --> 보안에 good
- 요청경로에 해당 파일이 없으면 알아서 next를 호출함
3) body-parser
- 요청의 본문에 있는 데이터를 해석해서 req.body 객체로 만들어주는 미들웨어
- form 데이터 or AJAX 요청의 데이터 처리
- 멀티파트(이미지, 영상, 파일) 데이터 처리는 불가
- app.use(express.json());
- app.use(express.urlencoded({extended:false})); // 주소형식으로 데이터 보냄
- express 4.16.0 버전부터 body-parser 미들웨어 일부 기능이 express에 내장되어 따로 설치할 필요 없음
- 직접 설치해야 하는 경우 : Raw, Text 형식의 데이터
- app.use(bodyParser.raw()); // req 본문이 버퍼 데이터일 때
- app.use(bodyParser.text()); // req 본문이 텍스트 데이터일 때
4) cookie-parser
- 요청에 동봉된 쿠키를 해석해 req.cookiees 객체로 만듦
- app.use(cookieParser(비밀 키));
- 첫 번째 인수로 비밀 키를 넣을 수 있음
- 서명된 쿠키가 있는 경우, 제공한 비밀 키를 통해 해당 쿠키가 내 서버가 만든 쿠키임을 검증 가능
- 쿠키는 클라이언트에서 위조하기 쉬우므로 비밀 키를 통해 만들어낸 서명을 쿠키 값 뒤에 붙임
- 서명이 붙으면 쿠키가 name=zero.sign과 같은 모양이 되고 서명된 쿠키는 req.signedCookies 객체에 들어있게됨
++ 쿠키를 생성/제거하려면 res.cookie, res.clearCookie 메서드 사용
res.cookie('name', 'zero', {
expires: new Date(Date.now() + 900000),
httpOnly: true,
secure: true,
});
res.clearCookie('name','zero',{httpOnly: true, secure: true });
- 쿠키를 지우려면, 키와 값 외에 옵션도 정확히 일치해야 함.
- expires나 maxAge는 일치할 필요 X
- signed : true로 설정하면 쿠키 뒤에 서명이 붙음, 서명옵션 켜두기
- 서명을 위한 비밀 키는 cookieparser 미들웨어에 인수로 넣은 `process.env.COOKIE_SECRET` 이 됨.
유익한 글이었습니다.