Notice
Recent Posts
Recent Comments
Link
«   2025/12   »
1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30 31
Tags
more
Archives
Today
Total
관리 메뉴

앵코딩

1. react,nodejs 게시판 (1) - Koa 본문

React/3

1. react,nodejs 게시판 (1) - Koa

miaee 2023. 6. 25. 20:42

Koa란?

Node.js환경에서 웹 서버 구축시 Express, Hapi, Koa등 웹프레임워크를 사용함

Express 는 미들웨어, 라우팅, 템플릿, 파일 호스팅 같은 다양한 기능이 자체적으로 내장

Koa는 미들웨어 기능만 갖추고 있으며 나머지는 다른 라이브러리 적용하여 사용

=> 필요한 기능들만 붙여 서버를 만들 수 있어 가벼움

async, await 문법을 정식으로 지원하여 비동기 작업이 수월

 

koa 프레임 워크 설치

npm add koa

 

 

ESLint란?

문법 검사 도구이며 , 코드를 작성할 때 실수할 시 에러또는 경고 메시지를 에디터에서 바로 확인할 수 있게 해줌

npx eslint --init

 

 

Koa 기본 사용법

// src/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");
});

 

const Koa = require("koa");

const app = new Koa();

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

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

// app.use 함수는 미들웨어 함수를 애플리케이션에 등록
// ctx : Context의 줄임말 => 웹 요청 ,응답에 관한 정보
// next : 현재 처리중인 미들웨어의 다음 미들웨어를 호출

// 미들웨어는 app.use를 사용하여 등록되는 순서대로 처리함
// next를 호출하지 않으면 다음 미들웨어는 처리X
app.use((ctx) => {
  ctx.body = "hello world";
});

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

 

...

app.use((ctx, next) => {
  console.log(ctx.url);
  console.log(1);
  // authorized=1 이라는 쿼리 파라미터가 포함되어있으면 미들웨어를 처리해주고 아니면 처리X
  if (ctx.query.authorized !== "1") {
    ctx.status = 401;
    return;
  }
  next();
});

...

Comments