공부하기/React

[React] Koa를 이용한 개발 / Koa, koa-router, nodemon

다섯자두 2022. 3. 7. 18:11

다음은 책 리액트를 다루는 기술을 읽고 공부한 내용을 바탕으로 작성된 글입니다.


 

const Koa = require('koa');

const app = new Koa();

// ctx : 웹 요청과 응답에 관한 정보가 담김
// next : 현재 처리 중인 미들웨어의 다음 미들웨어를 호출하는 함수

app.use(async (ctx, next) => {
  console.log(ctx.url);
  console.log(1);
  if (ctx.query.authorized !== '1') {
    ctx.status = 401; //unauthorized
    return;
  }
  // next() 함수는 Promise를 반환한다.

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

  // next().then(() => {
  //   console.log('END');});
});

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

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

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

 


nodemon : 코드를 변경할 때마다 서버를 자동으로 재시작해준다.

- 터미널

yarn add --dev nodemon

- package.json

"scripts" : {
	"start" : "node src",
    "start:dev" : "nodemon --watch src/ src/index.js"
    }

: nodemon은 src 디렉터리를 주시하고 있다가, 해당 디렉터리 내부의 어떤 파일이 변경되면 src/index.js를 재시작한다.

 

 


koa-router 

- 터미널 

yarn add koa-router

- index.js

const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

// 라우터 설정
router.get('/', (ctx) => {
  ctx.body = '홈';
});
router.get('/about', (ctx) => {
  ctx.body = '소개';
});

// app 인스턴스에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());

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

라우트 파라미터와 쿼리

라우터의 파라미터를 설정할 때에는 /about/:name 형식으로 콜론(:)을 사용하여 라우트 경로 설정

파라미터가 있을 수도 없을 수도 있다면 파라미터 이름 뒤에 물음표 사용 /about/:name?

 

url 쿼리의 경우, 해당 값을 ctx.query에서 조회 가능하며 쿼리 문자열을 자동으로 객체 형태로 파싱해준다.

문자열 형태의 쿼리 문자열을 조회해야 할 때는 ctx.querystring을 사용.

 

const Koa = require('koa');
const Router = require('koa-router');

const app = new Koa();
const router = new Router();

// 라우터 설정
router.get('/', (ctx) => {
  ctx.body = '홈';
});

router.get('/about/:name?', (ctx) => {
  const { name } = ctx.params;
  // name의 존재 유무에 따라 다른 결과 출력
  ctx.body = name ? `${name}의 소개` : '소개';
});

router.get('/posts', (ctx) => {
  const { id } = ctx.query;
  ctx.body = id ? `post #${id}` : 'post id가 없습니다.';
});

// app 인스턴스에 라우터 적용
app.use(router.routes()).use(router.allowedMethods());

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