Koa - next generation web framework for node.js
Introduction Koa is a new web framework designed by the team behind Express, which aims to be a smaller, more expressive, and more robust foundation for web applications and APIs. By leveraging async functions, Koa allows you to ditch callbacks and greatly
koajs.com
Koa는 미들웨어 기능만 갖추고 있고, 라우팅, 템플릿 등 다양한 기능이 내장되어 있지 않아 다른 라이브러리를 적용해야 합니다. 이 말은, Koa는 필요한 것만 설치함으로써 더욱 가볍게 백엔드를 구성할 수 있다는 것입니다.
npm i koa
서버 띄우기
koa 라이브러리를 설치한 후에는 다음과 같이 작성하여 서버를 띄울 수 있습니다. express랑 많이 비슷합니다.
const koa = require("koa");
const app = new koa();
const PORT = 4000;
app.use((ctx) => {
ctx.body = "hello world";
});
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
});
미들웨어 함수 (ctx, next) => ...
앞서 화면을 렌더하기 위해 ctx를 사용했습니다. 미들웨어 함수는 ctx, next라는 두 인자를 받습니다.
ctx는 req, res를 합친 객체입니다.
ctx.status, ctx.url, ctx.params, ctx.query, ctx.method,
ctx.request.body
등등 객체의 속성이나 메서드를 이용해 기존에 사용하던 방식을 잘 처리할 수 있습니다.
express와 마찬가지로 next를 사용하지 않을거면 부르지 않아도 됩니다.
// express
(req, res, next) => ...
//koa
(ctx, next) => ...
express와 마찬가지로 위에어부터 아래대로 차례로 출력되며, next를 만나면 다음으로 넘겨줍니다.
const koa = require("koa");
const app = new koa();
const PORT = 4000;
app.use((ctx, next) => {
console.log("middelware!");
console.log(ctx.url);
next();
});
app.use((ctx) => {
ctx.body = "hello world";
});
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
});
여기서 koa의 next에 독특한 점은 next 함수를 호출하면 Promise를 반환한다는 것입니다.
다음과 같이 next() 이후 then을 통해 문자열을 출력하도록할 수 있습니다.
app.use((ctx, next) => {
if (ctx.query.authorized !== "1") {
ctx.status = 401;
return;
}
next().then(() => console.log("print me"));
});
async/await를 이용해 위와 동일한 동작을 좀 더 간결하게 처리할 수도 있습니다.
app.use(async (ctx, next) => {
if (ctx.query.authorized !== "1") {
ctx.status = 401;
return;
}
await next();
console.log("print me");
});
필수 미들웨어 적용
bodyparser를 예로 설명하겠습니다.
npm i koa-bodyparser
설치 후에 express에서 처럼 그냥 라우트를 거치기 전에 적용시켜 주기만 하면 됩니다.
const Koa = require("koa");
const Router = require("koa-router");
const bodyParser = require("body-parser");
const api = require("./api");
const app = new Koa();
const router = new Router();
const PORT = 4000;
router.use("/api", api.routes());
// 상단에 위치시켜도 되지만 koa 인스턴스에 라우터를 적용하기 전에만 위치시키면 된다.
app.use(bodyParser());
app.use(router.routes()).use(router.allowedMethods());
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
});
koa-router
express에서는 express.Router를 곧장 사용하면 되었지만 koa에서는 router가 내장되어있지 않으니 따로 설치해야 합니다.
npm i koa-router
사용법도 꽤나 비슷하죠? 당연히 router.get 외에도 post. delete 등을 넣을 수도 있습니다.
const Koa = require("koa");
const Router = require("koa-router");
// koa, router 인스턴스 생성
const app = new Koa();
const router = new Router();
const PORT = 4000;
// 라우터 생성
router.get("/", (ctx) => {
ctx.body = "home";
});
router.get("/about", (ctx) => {
ctx.body = "about";
});
// app 인스턴스에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
});
파라미터와 쿼리는 다음과 같은 방식으로 url에서 추출해서 사용할 수 있습니다.
router.get("/about/:me?", (ctx) => {
// ctx.params
console.log(ctx.params.me);
// ctx.query
console.log(ctx.query);
ctx.body = `what`;
});
라우트를 모듈로 분리하기 위해서는 다음과 같이 해주면 됩니다.
const Router = require("koa-router");
const api = new Router();
api.get("/test", (ctx) => {
ctx.body = "test 성공";
});
module.exports = api;
const Koa = require("koa");
const Router = require("koa-router");
const api = require("./api");
const app = new Koa();
const router = new Router();
const PORT = 4000;
router.use("/api", api.routes());
app.use(router.routes()).use(router.allowedMethods());
app.listen(PORT, () => {
console.log(`http://localhost:${PORT}`);
});
'Node, Nest, Deno > 🚀 Node.js (+ Express)' 카테고리의 다른 글
노드 내장 모듈 util의 util.pomisify 사용하기 (0) | 2020.07.30 |
---|---|
[koa] KOA 백엔드의 라우팅 폴더 구조 (0) | 2020.07.30 |
chained route handlers (0) | 2020.07.02 |
sharp를 활용한 image resizing + buffer 이해하기 (0) | 2020.06.29 |
express-flash 사용 (0) | 2020.06.22 |