Morgan
- 요청과 응답을 기록하는 라우터
- GET / 404 2.000ms -9
- http method
- 요청 경로
- 응답 코드
- 응답 시간
- 응답 용량
const morgan = require('morgan');
const app = express();
app.use(morgan('dev'));
app.get 요청이 발생했을 때
console에 다음과 같이 출력된다.
GET / 404 2.000ms -9
BodyParser
app.use(express.json());
app.use(express.urlencoded({extended: true}));
- express.json : 클라이언트에서 json 데이터로 요청을 보냈을 때 그 데이터를 파싱해서 req.body로 넣어줌
- express.urlencoded : form submit시 form을 파싱해주는 등 알아서 데이터를 파싱해준다.
- extended true : 폼 파싱할 떄 쿼리스트링을 어떻게 처리할 것인지 true는 qs라는 모듈을 사용함.
- 폼 데이터 내의 이미지 또는 파일은 urlencoded가 처리하지 못한다.
CookieParser
- 요청 헤더의 쿠키를 해석해주는 미들웨어
- req.cookies안에 쿠키가 들어있음.
- 쿠키에 옵션을 지정할 수 있다.
- 쿠키 지우기를 지울 떄는 expries와 maxAge를 제외한 모든 옵션이 일치해야 한다.
const cookieParser = require('cookie-parser');
app.use(cookieParser('crypto'));
app.get('/', (req, res) => {
req.cookies;
res.cookie('name', encodeURIComponent(name), {
expires: new Date(),
httpOnly: true,
path: '/',
});
res.clearcookie('name', encodeURIComponent(name), {
httpOnly: true,
path: '/',
});
res.sendFile(path.join(__dirname, 'index.html'));
});
Static
- 정적인 파일들을 제공하는 미들웨어
- 읽어야 하는 파일이 있을 때 fs.readFile로 직접 읽을 필요 없음
- 요청하는 파일이 없으면 알아서 next를 호출해서 다음 미들웨어로 넘어감
- 파일을 발견했다면 다음 미들웨어 실행 안됨
- 요청 경로와 실제 경로를 다르게 설정할 수 있음.(보안에 좋다.)
app.use('요청경로', express.static(path.join('실제경로')));
app.use('/', express.static(path.join(__dirname, 'public')));
미들웨어 간 순서의 중요성
- static같은 경우, 파일을 반환하면 next가 실행되지 않기 때문에 불필요한 성능 저하가 일어나지 않게 하기 위해
위쪽에 두는 경우가 있다.
- static을 제외한 대다수는 next()를 실행하기 때문에 정적파일만 반환하면 되는 static입장에서 불필요한 프로세스이다.
app.use(morgan('dev')); // 무조건 실행
app.use('/', express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(express.json());
app.use(express.urlencoded({extended: true}));
Express-session
- 세션 관리용 미들웨어
- 세션 쿠키에 대한 설정 가능
app.use(
session({
resave: false,
saveUninitialized: false,
secret: 'crypto',
cookie: {
httpOnly: true,
},
})
);
app.get('/', (req, res, next) => {
req.session.id = 'hello';
res.sendFile(path.join(__dirname, 'index.html'));
});