반응형

 

 

이전 포스팅에 이어서, 간단한 라우팅을 적용해보자.

 

(이전 포스팅)

Express 간단한 서버 세팅 👇

https://woojin.tistory.com/24

 

 

 

 


라우팅(Routing)이란?

애플리케이션 엔드포인트(URI)의 정의, 그리고 URI가 클라이언트 요청에 응답하는 방식을 말한다.

route의 동명사형인데, 이거 콩글리시 아닌가? (콩글리시 죽어)

route는 '루트'로 발음한다. 우리가 흔히 아는 '경로'라는 단어가 맞다.

 

쉽게 말하면, 요청이 URI에 들어오면 그것을 어느 경로로 분기시켜줄지 즉, 어디로 보내줄지 정의하는 것을 의미한다.

 

 

Express의 라우팅 기본 구조

src 폴더에 index.ts가 있다.

src 폴더에 api 폴더를 만든다.

api 폴더에는 index.ts, user.ts를 생성한다.

 

localhost:8000/api/user에 클라이언트의 요청이 들어오면

우선 ../src/index.ts 로 간다.

그곳에서 분기되어 ..src/api/index.ts 로 간다.

그곳에서 user.ts로 가라는 명령을 받아 ..src/api/user.ts로 이동한다.

 

즉, 요청은 가장 처음 ../src/index.ts 로 이동하고,

각 폴더의 index.ts 들의 명령을 통해 정확한 위치로 이동하여 요청을 수행한다.

 

자, 이제 간단한 라우팅을 구현해보자.

 

 

assignment/src/api/user.ts 생성

* 프로젝트명 : assignment

// user.ts
import express, { Request, Response, Router } from 'express';

const router: Router = express.Router();

router.get('/', (req: Request, res: Response) => {
    return res.status(200).json({
        status: 200,
        message: '유저 조회 성공'
    });
});

module.exports = router;

 

 

get 메서드를 간단하게 정의했다.

json response를 router 객체에 담고, 모듈로 반환한다.

 

 

assignment/src/api/index.ts 생성

// index.ts

import express, { Router } from 'express';

const router: Router = express.Router();

router.use('/user', require('./user'));

module.exports = router;

/api/user 엔드포인트에 요청이 들어오면 user.ts 파일을 실행하게 한다.

 

 

assignment/src/index.ts 수정

/api 로 요청이 들어왔을 때, src/api/index.ts 로 보내 올바르게 분기하도록 설정해야한다.

지금은 요청이 src/index.ts 로 들어왔을 때, src/api/index.ts로 보내주도록 설계되지 않았다.

 

// ../src/index.ts

import express, { Request, Response, NextFunction } from 'express';

const app = express();

app.use(express.json());	// request body를 express에서 json으로 받아 온다.

app.use('/api', require('./api'));	// /api 엔드포인트에 요청이 들어오면 api 폴더로 분기한다.

app.get('/', (req: Request, res: Response, next: NextFunction) => {
    res.send('Hi! This is my first express server. My name is Woojin.');
});

app.listen('8000', () => {
    console.log(`
    #############################################x
        🛡️ Server listening on port: 8000 🛡️
    #############################################    
    `)
})

 

 

localhost:8000/api/user 접속

브라우저에 localhost:8000/api/user 를 입력하고 접속한다.

서버가 구동되고 있지 않다면, 터미널에 'yarn run dev'를 실행시킨다.

 

../src/api/user.ts에 작성한 대로 응답을 받을 수 있다.

이렇게 간단한 라우팅이 완료되었다.

 

 

 

 

반응형

+ Recent posts