• 타입스크립트로 백엔드 Express 시작하기 (Node.js & Express + TypeScript)

    2021. 3. 9.

    by. kimyang-Sun

    node.js

     

    백엔드 API 개발을 위한 node.js 를 시작해보려고 합니다.

    node.js의 사용을 더 편리하게 해주는 Express 프레임워크를 설치하여 이용하겠습니다.

     

    npm init

     

    우선 해당 디렉토리에서 npm init으로 프로젝트를 시작하여 이름이나 버전, 설명등을 정해줍니다.

    그러면 디렉토리에 package.json 파일이 생성됩니다.

     

    다음으로 설치해주어야 하는것들이 있습니다.

     

    yarn add express
    yarn add -D typescript ts-node @types/node @types/express tsc-watch // 개발모드로 설치

     

    설치가 완료되면 node_modeuls 디렉토리도 생성될거에요.

    설치된것들 중에 ts-node는 타입스크립트를 실행주기 때문에 필요하고

    tsc-watch는 저장할때마다 실시간으로 컴파일해서 서버에 반영해주기 때문에 필요합니다.

     

     

    // package.json
    
    {
      "name": "write-back",
      "version": "0.1.0",
      "description": "React Write App (Back)",
      "main": "index.js",
      "scripts": {
        "start": "tsc-watch --onSuccess \"ts-node dist/app.js\""
      },
      "dependencies": {
        "express": "^4.17.1"
      },
      "devDependencies": {
        "@types/express": "^4.17.11",
        "@types/node": "^14.14.32",
        "tsc-watch": "^4.2.9",
        "typescript": "^4.2.3"
      }
    }
    

     

    pakage.json 파일에서 script에

    "start""tsc-watch --onSuccess \"ts-node dist/app.js\"" 를 추가해줍니다.

    watch를 성공하면 dist/app.js를 실행시킨다는 의미입니다.

     

    이제 tsc를 입력하거나 yarn start로 서버를 시작하게되면 컴파일되면서 tsconfig.json 파일이 만들어질거에요.

     

    // tsconfig.json
    
    {
      "compilerOptions": {
        "target": "es5",
        "module": "commonjs",
        "outDir": "dist"
      },
      "include": ["src/**/*"],
      "exclude": ["node_modules"]
    }
    

     

    기본값과 함께 주석처리된 부분들이 많은데 이렇게 작성해줍니다.

    저는 타입스크립트 파일이 src 디렉토리에 들어가있기 때문에 include를 저렇게 작성해주었습니다.

    exclude는 컴파일을 제외시킬 폴더입니다.

    (애초에 src 디렉토리 내부의 파일들만 컴파일해줘서 굳이 작성해주지 않아도 되지만 그냥 해줬습니다.)

     

    이제 app.ts를 보겠습니다.

     

    // src/app.ts
    
    import * as express from 'express';
    import postRouter from './routes/post';
    const app: express.Application = express();
    
    // get
    app.get('/', (req: express.Request, res: express.Response) => {
      res.send('hello express');
    });
    
    app.get('/posts', (req: express.Request, res: express.Response) => {
      res.json([
        { id: 1, content: 'hello' },
        { id: 2, content: 'hello2' },
        { id: 3, content: 'hello3' },
      ]);
    });
    
    // Express Router 적용하기
    app.use('/post', postRouter);
    
    // 3010 포트로 서버 실행
    app.listen(3010, () => {
      console.log('실행중');
    });

     

    해당 파일에 Express Router도 넣어줬습니다.

    Router는 따로 디렉토리를 만들어주고 파일도 따로 만들어주고 app.use에 넣어주시면 됩니다.

    라우터 파일에 있는 것들이 '1' ,'2', '3' 이런식이면 /post/1, /post/2, /post/3 각각 이렇게 됩니다.

     

    yarn start

     

    이제 yarn start로 서버를 실행시켜보겠습니다.

     


    cmd 명령 프롬프트

     


    http://localhost:3010/


     

    서버 실행에 들어가있던 console.log('실행중')도 잘 나오고 로컬호스트 3010에 hello express도 잘 나옵니다.

    그리고 app.ts에 있는 posts도 확인하겠습니다.

     


     

    http://localhost:3010/posts


    잘 나오는것을 확인할 수 있습니다.

     

     

    디렉토리 구조

     

    get같은 경우는 브라우저에서 확인이 가능하지만 다른 요청들은 확인이 불가능하여

    postman 을 설치하여 작업하면 좋습니다.

     

    여러 요청들은 보통은 이렇게 사용합니다.

     

    • app.get = 가져오기
    • app.post = 생성,등록하기
    • app.put = 전체 수정하기
    • app.patch = 부분 수정하기
    • app.delete = 제거하기
    • app.options = 서버에게 요청을 알리기
    • app.head = Header만 가져오기

    댓글