본문 바로가기
  • 실행력이 모든걸 결정한다
Node.js/Express

[Express] Compression / app.use() / 정적 파일

by 김코더 김주역 2021. 7. 28.
반응형

1. Compression

Compression은 웹 사이트를 gzip으로 압축시켜서 로딩 속도가 빨라지게 도와주는 미들웨어다.

압축을 푸는 과정이 추가될지라도, 규모가 큰 웹 애플리케이션에서는 상당한 성능 상승효과를 기대할 수 있다.

 

설치

npm install compression --save

 

적용

const express = require('express')
const compression = require('compression'); //★
const app = express()

...
app.use(compression()); //★

 

 

 

2. app.use()

const express = require('express')
...
const app = express()

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use(compression())
app.use(myMW)

express의 use() 메소드는 미들웨어 함수를 로드 시켜주는 역할을 한다.

use() 메서드의 인자 값은 메서드이기 때문에, 만약 여러분이 직접 미들웨어를 만들어 넣고 싶다면 여러분이 만든 메서드의 마지막에 next()를 호출시키면 된다. next()는 다음 미들웨어로 현재 요청을 넘기는 역할을 하며, next()를 작성하지 않으면 요청이 넘어가지 않는다.

function myFunc(request, response, next) {
   ...
   next();
}

 

미들웨어가 필요 없는 요청에도 미들웨어가 동작된다면 이는 비효율적일 것이다.
이를 개선하기 위해, 다음과 같이 특정 경로 요청에 대해 실행할 미들웨어를 지정할 수도 있다.

// func1, func2, func3은 메소드
app.use('/user/:id', func1, func2, func3);

※ next('route') : 주소와 일치하는 다음 라우터로 건너뛰기

 

 

 

3. 정적 파일

웹 프레임워크에서 프로젝트 내의 정적 파일에 접근하는 경우에 대해서는 별도로 신경을 써줘야 한다.

 

예를 들어, 다음과 같은 케이스를 보자.

프로젝트 내에 static/sphere.jpg 경로로 이미지 파일을 저장했다.

 

<home.ejs>

<!doctype html>
<html>
    <head>
        <title>send</title>
    </head>
    <body>
        <img src="http://localhost:3000/static/sphere.jpg" width="500px">
    </body>
</html>

 

그러나, 파일을 불러올 수 없었다.

 

왜냐하면, 서버로 URL 요청이 들어오면 컨트롤러 부분에서 요청을 가로채기 때문이다.

 

"http://localhost:3000/static/sphere.jpg" 요청이 서버로 들어왔지만, 컨트롤러 부분에서는 '/hello'에 해당하는 요청에 대한 처리만 작성해두었기 때문에 해당 파일에 접근할 수 없었던 것이다.

 

<수정 전 app.js>

const express = require('express')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const app = express()

app.set("view engine", "ejs")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))

app.get('/hello', function(req,res){
    res.render('home');
})

app.listen(3000, ()=>console.log('Example app listening on port 3000!'))

 

이런 경우에는 다음과 같은 방법으로 해결할 수 있다.

정적 파일에 접근할 수 있도록 하는 미들웨어를 app.use() 메소드로 적용시켜주면 되는 것이다.

app.use(A, express.static(B))

A : B 디렉토리에 접근하기 위한 요청 경로

B : 정적 파일들이 모여 있는 최상위 디렉토리

 

다음 코드는 위의 코드를 적용한 최종 코드이며, 추가된 코드를 //★ 주석으로 표시 했다.

 

<수정 후 app.js>

const express = require('express')
const bodyParser = require('body-parser')
const ejs = require('ejs')
const app = express()

app.set("view engine", "ejs")
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({extended: true}))
app.use('/static', express.static('static')) //★

app.get('/hello', function(req,res){
    res.render('home');
})

app.listen(3000, ()=>console.log('Example app listening on port 3000!'))

 

파일에 성공적으로 접근했다.

 

반응형

댓글