[Node.js] Koa 프레임워크 사용하기

🌊·2021년 12월 30일
0

Node.js

목록 보기
1/3

Koa 프레임워크

  • express의 기존 개발팀이 개발한 프레임워크
  • 미들웨어 기능만 갖추고 있으며 나머지는 다른 라이브러리를 적용하여 사용한다.
  • async / await 문법을 정식으로 지원하기 때문에 비동기 작업을 더 편하게 관리할 수 있다.

express는 미들웨어, 라우팅, 템플릿, 파일 호스팅 등과 같은 기능이 자체적으로 내장되어 있다.
그래서 express가 koa보다 무겁다.

작업 환경 준비

Node 설치 확인

$ node --version

package.json 파일 생성

$ yarn init -y

프로젝트를 시작할 때 초기화를 하려면 사용한다.

Koa 프레임워크 설치

$ yarn add koa

ESLint와 Prettier 설정

$ yarn add --dev eslint
$ yarn run eslint --init

--dev는 개발용 의존 모듈로 설치한다는 의미이다.
자바스크립트 문법을 검사하고 깔끔한 코드를 작성하기 위해서 사용한다.
ESLint와 Prettier를 사용하려면 VS Code 마켓플레이스에서 확장 프로그램을 설치해야 사용이 가능하다.

.prettierrc

{
  "singleQuote": true,
  "semi": true,
  "useTabs": false,
  "tabWidth": 2,
  "trailingComma": "all",
  "printWidth": 80
}

Koa 기본 사용

index.js

const Koa = require('koa');

const app = new Koa();

app.use((ctx) => {
  ctx.body = 'hello world';
});

app.listen(4000, () => {
  console.log('Listening to port 4000');
});

서버 실행

$ node src

미들웨어

Koa 애플리케이션은 미들웨어의 배열로 구성되어 있다.

미들웨어 함수 구조

(ctx, next) => {
}
  • ctx: Context의 줄임말, 웹 요청과 응답에 관한 정보를 가지고 있다.
  • next: 현재 처리 중인 미들웨어의 다음 미들웨어를 호출하는 함수

미들웨어는 app.use를 사용하여 등록되는 순서대로 처리한다.
next()가 없으면 다음 app.use를 실행하지 않는다.

next 함수는 Promise를 반환

Express와 차별되는 부분이다.
next함수가 반환하는 Promise는 다음에 처리해야 할 미들웨어가 모두 끝나야 완료된다.

index.js

app.use((ctx, next) => {
  console.log('3');
  next().then(() => {
    console.log('END');
  });
});

app.use((ctx, next) => {
  console.log('1');
  next();
});

app.use((ctx) => {
  console.log('2');
});

출력 순서는 '3', '1', '2', 'END' 순서대로 출력된다.

async / await 적용

index.js

app.use(async (ctx, next) => {
  // 조건부 미들웨어 처리
  if (ctx.query.authorized !== '1') {
    ctx.status = 401; // Unauthorized
    return;
  }
  console.log('1');

  await next();
  console.log('END');
});

app.use((ctx) => {
  console.log('2');
});

nodemon 사용

서버 코드를 변경할 때 마다 서버를 자동으로 재시작해주는 모듈이다.

$ yarn add --dev nodeman

package.json

{
  (...)
  "devDependencies": {
    "eslint": "^8.5.0",
    "nodemon": "^2.0.15"
  },
  "scripts": {
    "start": "node src",
    "start:dev": "nodemon --watch src/ src/index.js"
  }
}

$ yarn start : 재시작이 필요 없을 때
$ yarn start:dev : 재시작이 필요할 때

0개의 댓글