3. Backend/NestJS / / 2024. 3. 8. 18:35

[코드팩토리 NestJS 강의] nodeJS와 Express를 사용해서 기본적인 서버 만들기

1. http패키지만 사용하여 server 만들기

// http패키지만 사용하여 server 만들기
// import http from 'http' 와 동일한 문법
const http = require("http");
const url = require("url");

// localhost는 127.0.0.1이라는 IP를 뜻함, 이것을 look back이라고 표현 = 서버를 실행한 컴퓨터
// 현재 컴퓨터에 3000번 포트에다가 서버를 실행하기 위해서 변수들을 선언한 것
const host = "localhost";
const port = 3000;

// 서버 만드는 방법
// http.createServer를 하고, 서버를 만들고 나서 어떤 응답들을 보내줄지 설정하는것을 콜백함수에 넣어줌
// req = request = 요청 : 서버에 무언가를 달라고 요청하는 입장에서 정보전달하는 역할을함 (요구하는쪽)
// res = response = 응답 : 요청을 기반으로, 요청에서 원하는 답을 되돌려주는것
const server = http.createServer((req, res) => {
  const path = url.parse(req.url).pathname;

  // writeHead에는 1. status코드를 넣을 수 있다 2. header를 넣을 수 있다.
  // 이 서버를 실행하면, <h1>Hello World</h1>를 반환을 해줌
  // 이 코드는 어떤요청이와도 <h1>Page</h1>가 나오는 코드를 작성했기에 그거에 맞는 화면이 뜸
  if (path === "/") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>Home Page</h1>");
  } else if (path === "/post") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>Post Page</h1>");
  } else if (path === "/user") {
    res.writeHead(200, { "Content-Type": "text/html" });
    res.end("<h1>User Page</h1>");
  } else {
    res.writeHead(404, { "Content-Type": "text/html" });
    res.end("<h1>404 Page Not Found!</h1>");
  }
});

// http.createServer로 서버를 생성하는것만으로는 부족하다
// 서버를 생성했으니, 서버를 실행해줘야함
// createServer가 반환해주는 값이 있는데, 반환해주는 값을 const server라는 변수에 넣어줌

// listen은 어떤 호스트와 어떤포트에서 듣고있게할것인지 = 어디에서 실행할것인지
// 1파라미터 : port, 2파라미터 : host, 3파라미터 : 함수
// 함수는 server.listen을 해서 서버가 실행이 되었을때, 무언가를 바로 실행할 수 있는 함수이다.
server.listen(port, host, () => {
  console.log("server running on http://localhost:3000");
});

// vscode에 터미널을 열어서 node 폴더명(node 1_server.js)을 적어주면 된다.
// 그럼 결과로 바로 실행하는 함수인 console.log에 있는 문자가 보임

 

2. express를 사용하여 server 만들기

// express를 사용하여 server 만들기
// yarn add express해야함
const express = require("express");

// app이라는 변수를 만들고, express를 함수처럼 실행시킴
// 이러면, app에다가 우리가 원하는 endpoint들을 붙일 수 있음
const app = express();

// app. 을 하면 http에 해당하는 모든 메서드들을 함수로 받아볼수 있다
// 1파라미터 : path, 2파라미터 : 콜백함수 (req, res)=>{}

// if문으로 분기처리하는것보다 더 간결한 코드
// express의 장점 : 분기처리가 자동으로 됨, get요청별로 관련된 것들을 따라서 라우팅이 들어감
app.get("/", (req, res) => {
  res.send("<h1>Home Page</h1>");
});
app.get("/post", (req, res) => {
  res.send("<h1>Post Page</h1>");
});
app.get("/user", (req, res) => {
  res.send("<h1>User Page</h1>");
});
app.get("/", (req, res) => {
  res.send("<h1>Home Page</h1>");
});
// 404에 대한 페이지는 path를 받지않고 아래와 같이 씀
// 즉 위에 응답들에 걸리지 않으면 use에 있는 거에 걸림
app.use((req, res) => {
  res.status(404).send("<h1>404 Page Not Found!</h1>");
});
app.post();
app.delete();
app.put();

// express도 app.listen을 해야 실행이 됨
// 1파라미터 : 포트, 2파라미터 : 콜백함수 (포트가 실행이되면 실행이될 함수를 정의함)
app.listen(3000, () => {
  console.log("server running on http://localhost:3000");
});

 

 

NestJS 설치가 되었는지 확인하기 위해서는 터미널에 nest라 치면 아래와 같이 나와야한다

82103@DESKTOP-2IG24QK MINGW64 ~
$ nest
Usage: nest <command> [options]

Options:
  -v, --version                                   Output the current version.
  -h, --help                                      Output usage information.

Commands:
  new|n [options] [name]                          Generate Nest application.
  build [options] [app]                           Build Nest application.
  start [options] [app]                           Run Nest application.
  info|i                                          Display Nest project details.
  add [options] <library>                         Adds support for an external library to your project.
  generate|g [options] <schematic> [name] [path]  Generate a Nest element.
    Schematics available on @nestjs/schematics collection:
      ┌───────────────┬─────────────┬──────────────────────────────────────────────┐
      │ name          │ alias       │ description                                  │
      │ application   │ application │ Generate a new application workspace         │
      │ class         │ cl          │ Generate a new class                         │
      │ configuration │ config      │ Generate a CLI configuration file            │
      │ controller    │ co          │ Generate a controller declaration            │
      │ decorator     │ d           │ Generate a custom decorator                  │
      │ filter        │ f           │ Generate a filter declaration                │
      │ gateway       │ ga          │ Generate a gateway declaration               │
      │ guard         │ gu          │ Generate a guard declaration                 │
      │ interceptor   │ itc         │ Generate an interceptor declaration          │
      │ interface     │ itf         │ Generate an interface                        │
      │ library       │ lib         │ Generate a new library within a monorepo     │
      │ middleware    │ mi          │ Generate a middleware declaration            │
      │ module        │ mo          │ Generate a module declaration                │
      │ pipe          │ pi          │ Generate a pipe declaration                  │
      │ provider      │ pr          │ Generate a provider declaration              │
      │ resolver      │ r           │ Generate a GraphQL resolver declaration      │
      │ resource      │ res         │ Generate a new CRUD resource                 │
      │ service       │ s           │ Generate a service declaration               │
      │ sub-app       │ app         │ Generate a new application within a monorepo │
      └───────────────┴─────────────┴──────────────────────────────────────────────┘

 

 

nestJS 환경설정을 깔아주는 코드 입력

82103@DESKTOP-2IG24QK MINGW64 ~
$ nest new nestjs_serve
⚡  We will scaffold your app in a few seconds..

? Which package manager would you ❤️  to use? (Use arrow keys)
? Which package manager would you ❤️  to use? npm
CREATE nestjs_serve/.eslintrc.js (688 bytes)
CREATE nestjs_serve/.prettierrc (54 bytes)
CREATE nestjs_serve/nest-cli.json (179 bytes)
CREATE nestjs_serve/package.json (2020 bytes)
CREATE nestjs_serve/README.md (3413 bytes)
CREATE nestjs_serve/tsconfig.build.json (101 bytes)
CREATE nestjs_serve/tsconfig.json (567 bytes)
CREATE nestjs_serve/src/app.controller.ts (286 bytes)
CREATE nestjs_serve/src/app.module.ts (259 bytes)
CREATE nestjs_serve/src/app.service.ts (150 bytes)
CREATE nestjs_serve/src/main.ts (216 bytes)
CREATE nestjs_serve/src/app.controller.spec.ts (639 bytes)
CREATE nestjs_serve/test/jest-e2e.json (192 bytes)
CREATE nestjs_serve/test/app.e2e-spec.ts (654 bytes)

- Installation in progress... ☕
√ Installation in progress... ☕

🚀  Successfully created project nestjs_serve
👉  Get started with the following commands:

$ cd nestjs_serve
$ npm run start


                          Thanks for installing Nest 🙏
                 Please consider donating to our open collective
                        to help us maintain this package.


                   🍷  Donate: https://opencollective.com/nest

 

3. NestJS를 사용하여 server 만들기

import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  // Get() === Get('/')
  @Get()
  getHome() {
    return 'Home Page';
  }
  @Get('post')
  getPost() {
    return 'Post Page';
  }
  @Get('user')
  getUser() {
    return 'User Page';
  }
}
728x90
  • 네이버 블로그 공유
  • 네이버 밴드 공유
  • 페이스북 공유
  • 카카오스토리 공유