Node js Express 설정

강준호·2024년 2월 15일

NodeJs

목록 보기
1/7

1. node.ts 환경 세팅

(1) .gitignore 파일 만들기

git init
touch .gitignore
  • gitignore에 작성
node_modules
dist

(2) npm 타입스크립트 환경 세팅

npm init -y		//package.json 파일 생성	
npm i			//package-lock.json 파일 생성
npm i -D typescript ts-node @types/node		//node_modules 폴더 생성
npx tsc --init   		//tsconfig.json

npm i -D concurrently //dist 폴더

npm install express
npm install -D @types/express

npm install body-parser //bodyparser 설치
npm i jsonwebtoken

// tsconfig.json

"outDir": "./dist" declaration, "declarationMap", sourceMap, sourceRoot: "src" 주석 해제 를 주석해제하자.

package.json 에 dev,build,start 만들기

  • package.json 안에 scripts에서 test내용 지우고 아래 입력
"dev": "concurrently 'tsc --watch --project tsconfig.json' 'node --watch dist/app.js'",
"build": "tsc --project tsconfig.json",
"start": "node dist/app.js"

//추가 팁
,"prestart": "npm run dev"
  • npm run dev 실행시 dist폴더 생김

app.ts 에 express 로 설정

import express from "express";

const app = express();
const port = 5555;

app.listen(port, () => {
  console.log("서버 작동중");
});

2. 서버 만들기

  • express를 임포트, 서버는 5555로 설정
import express from 'express';

const app = express();
const port = 5555;

(2) bodyParser

  • 클라이언트인 html파일에서 서버로 보낼데이터를 파싱 (즉 서버에서 클라이언트의 요청을 알아들을 수 있게 해주는 역할)
npm install body-parser
  • bodyParser를 사용할 수 있도록 app.use 활용

app.use(bodyParser.json());

  • 사용 예시

//전체코드

import express from 'express';
import bodyParser from 'body-parser';

const app = express();
const port = 5555;

app.use(bodyParser.json());

app.get("/", (req, res) => {
    res.send("HelloWorld")
});
  • npm run dev 결과
  1. Json불러오기

(1) posts.json 파일 만들기

(2) 서버로 불러오기

  • 기본 구조 : express명.요청("경로", (요청, 응답) => {내용})

  • 전체 포스트 불러오기

app.get("/posts", (req, res) => {
    const postId = req.query.postId;
    if (postId) {
        const post = posts.find((post) => post.id === Number(postId));
        res.json(post);
    } else {
        res.json(posts);
    }
    res.json(posts)
});
  • npm run dev 결과
  • 개별 포스트 id 로 불러오기
app.get("/posts/:postId", (req, res) => {
    const postId = req.params.postId;
    const post = posts.find((post) => post.id === Number(postId));
})
  • 결과
app.get(/.*fly$/, (req, res) => {
  res.send('/.*fly$/')
})

정규표현식도 사용가능

0개의 댓글