express는 미들웨어, 라우팅, 템플릿, 파일 호스팅 등과 같은 기능이 자체적으로 내장되어 있다.
그래서 express가 koa보다 무겁다.
$ node --version
$ yarn init -y
프로젝트를 시작할 때 초기화를 하려면 사용한다.
$ yarn add koa
$ 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
}
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
를 실행하지 않는다.
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' 순서대로 출력된다.
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');
});
서버 코드를 변경할 때 마다 서버를 자동으로 재시작해주는 모듈이다.
$ 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
: 재시작이 필요할 때