RESTfull API

http 의 종류

GET, POST, PUT, PATCH

https://adventure-works.com/orders // Good

https://adventure-works.com/create-order // Avoid

의미를 알 수 있는 GET 을 사용하지 말 것.

명사로 사용해라

프로젝트 시작

(letsStart 폴더를 다운받는다.)

package.json

  {
    "scripts": {
      "build": "tsc",
      "start:dev": "tsc-watch --onSuccess \"node dist/app.js\"",
      "prestart": "npm run build",
      "start": "node dist/app.js"
    },
    "devDependencies": {
      "@types/node": "^15.3.0",
      "prettier": "^2.2.1",
      "tsc": "^2.0.3",
      "tsc-watch": "^4.2.9",
      "typescript": "^4.3.4"
    }
  }

하나씩 구성을 보면

  • “@types/node”: “^15.3.0”, : javascript의 type들을 가져오겠다.
  • “prettier”: “^2.2.1”, : formatter 지정
  • “tsc”: “^2.0.3”, : typescript 컴파일러
  • “tsc-watch”: “^4.2.9”, : 계속 파일을 (컴파일 될 때)지켜보고 있는 용도 (위의 스크립트로 사용됨)

npm run start : 이렇게 하게 되면 자동으로 prestart 를 실행하게 되고, npm run build가 실행 된다.

npm run buildtsc 로 매칭 되므로 타입스크립트 컴파일러에 의해 build되는 일련의 과정을 거친다고 보면 된다.

Expressjs 설치

npm i express

그리고 typescript 위에서 돌려야 하므로

npm i @types/express -D 를 실행시켜 준다.

(devDependencies에 추가하면 됨)

Getting Start

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port ${port}`)
})

express공식 홈페이지에 가면 위와 같은 파일이 있음을 확인할 수 있다.

이를 typescript로 바꿔주는 작업이 필요하다.

import * as express from 'express';

const app: express.Express = express()
const port = 8000

app.get('/', (req, res) => {
  res.send('Hello World!')
})

app.listen(port, () => {
  console.log(`Example app listening on port http://localhost:${port}`)
})

위와 같이 바꿔보았다. 94번째 줄

const app: express.Express = express()

위와 같이 app을 설정하면 Express의 인스턴스를 생성해주고

그러면 서버의 역할을 할 수 있게 되는 것이다.

app.get('/', (req, res) => {
  res.send('Hello World!')
})

이미 알고 있지만

req : request (FE/client 에서 보내는 요청) res : response (res.send를 사용하여 응답을 보낼 수 있음)

json 데이터 형식으로 보낼 수 있다.

get 방식이라면 / 뒤에 경로를 가져오게 되는 것임