const Koa = require('koa');

const app = new Koa();

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

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

미들웨어

  • Koa App은 미들웨어의 배열로 구성
  • app.use 함수를 이용해 미들웨어 함수를 app에 등록
  • 파라미터 ctx는 조금 전에 사용한, 두번째 파라미터는 next
  • ctx는 Context의 줄임말
    • 웹요청과 응담에 대한 정보
  • next는 현재 처리중인 미들웨어의 다음 미들웨어를 호출하는 함수
    • next 함수를 호출하지 않으면 다음 미들웨어 처리를 하지 않음
const Koa = require('koa');

const app = new Koa();

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

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

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

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

  • next를 중간에 뺀다면 그 이후의 미들웨어는 모두 무시
  • 특정 조건으로 미들웨어를 처리하도록 가능
app.use((ctx, next) => {
  console.log(ctx);
  console.log(1);
  if (ctx.query.authorized !== '1') {
    ctx.status = 401; // Unauthorrized
    return;
  }
  next();
});
  • http://localhost:4000/?authorized=1로 조회해야지만 hello world의 결과가 나옴
  • 웹 요청의 쿠키 혹은 헤더를 통해 처리가 가능
  • next 함수는 Promise를 반환
    • Express와 차별되는 부분
    • next 함수가 반환하는 Promise는 다음에 처리해야하는 미들웨어가 끝나야 완료

node 프로젝트 시작하기 전에 아래와 같이 환경을 구성하고 구현하자

yarn init -y  
yarn add koa  
yarn add --dev eslint  // dev는 개발용 의존 모듈로 설치, package.json에서 dev dependencies 쪽이 모듈의 버전 입력
yarn run eslint --init // javascript 문법 검사, 깔끔한 코드 작성

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

을 추가하고 Prettier에서 관리하는 코드 스타일은 ESLint에서 관리하지 않도록 설치

$ yarn add eslint-config-prettier 

.eslintrc.json의 파일은 아래와 같이 설정

{
  "env": {
    "browser": true,
    "commonjs": true,
    "es6": true,
    "node": true
  },
  "extends": ["eslint:recommended", "prettier"],
  "globals": {
    "Atomics": "readonly",
    "SharedArrayBuffer": "readonly"
  },
  "parserOptions": {
    "ecmaVersion": 2018
  },
  "rules": {
    "no-unused-vars": "warn", // 설정하지 않으면 사용하지 않는 변수에 대해서 Error
    "no-console": "off" // console.log를 사용하는것을 지양함.
  }
}

+ Recent posts