tech.junha.kr

[Express 미들웨어 라이브러리] morgan, helmet, cookie-parser, body-parser

1. morgan

Logging미들웨어: http 상태 코드, 접속 하는데 걸린 시간, 명령어 등을 기록한다.

npm i morgan
import morgan from "morgan"

app.use(morgan("dev"))

// morgan의 인자로 combined, tiny, dev 등이 존재한다.

2. helmet

다양한 HTTP 헤더를 설정하여 Express 응용 프로그램의 보안을 유지하도록 도와준다.

npm i helmet
import helmet from "helmet"

app.use(helmet())

쿠키 사용에 도움을 준다. 쿠키 헤더를 파싱하고, req.cookies를 쿠키 이름으로 키가 된 객체로 채운다.

npm i cookie-parser
import cookiePaser from "cookie-parser"

app.use(cookiePaser())

4. body-parser

express는 request를 처리할 때 body를 undeifned로 처리하고 있다.

때문에 body-parser 미들웨어를 사용하면 request의 body부분을 json 형태로 파싱하여 사용할 수 있다.

app.get('/', (req, res) => {
	console.log(req.body) // undefined
})

4.16.0 버전 부터는 body-parser가 내장되어있기 때문에 설치할 필요 없이 다음과 같이 쓴다.

// import bodyParser from "body-parser";
// app.use(bodyParser.urlencoded({ extended: false }));
// app.use(bodyParser.json());
app.use(express.urlencoded({ extended: false }));
app.use(express.json());