Backend/Node.js

Express

AIHYEONJI 2025. 4. 27. 12:24

1. Express

: Express 는 Node.js 환경에서 가장 널리 사용되는 웹 애플리케이션 프레임 워크로 , 서버를 쉽고 빠르게 구출 할 수 있도록 다양한 기능을 제공한다.

간단하게 라우팅 처리, 요청/응답 객체 관리, 미들웨어 설정, 정적 파일 제공, 템플릿 엔진 연결 등을 할 수 있어 개발 생산성을 크게 높여준다. 특히 RESTful API 구출에 최적화되어있음

 

1.1 app.js

const express = require("express");
const path = require("path");
const app = express();
const port = 3001;

// post 데이터 받는방법
app.use(express.urlencoded({ extended: true }));
// app.use(express.static("public"))   // 실제 폴더 이름
app.use("/static", express.static("public"));   // static URL 접근, public 실제폴더

app.set("view engine", "ejs");
// 파일경로를 views라고 통합하여 칭한다.
app.set("views", path.join(__dirname, "views"));

app.get("/", (req, res) => {
  res.send("<h2>홈페이지입니다. 다양한 기능을 테스트해보세요.</h2>");
});

// http://localhost:3001/user 에 id값 보내기
app.get("/user/:id", (req, res) => {
  res.send(`요청한 사용자 ID는 ${req.params.id}입니다.`);
});

app.get("/search", (req, res) => {
  const { keyword, number } = req.query;
  res.send(`검색어: ${keyword} 번호 :${number}`);
});

app.post("/submit", (req, res) => {
  const { name, age } = req.body;
  res.send(`이름 : ${name}, 나이 : ${age}`);
});

app.get("/hello", (req, res) => {
  res.render("hello", { name: "김사과" });
});

app.get("/posts", (req, res) => {
  const posts = [
    { title: "첫 번째 글", content: "내용입니다." },
    { title: "두 번째 글", content: "Express는 정말 어려워요~" },
  ];
  res.render("posts", { posts });
});

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

 

1.2. hello.ejs

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>안녕하세요</title>
  </head>
  <body>
    <h2>안녕하세요,<%=name%>님!</h2>
  </body>
</html>

 

1.3 post.ejs

<!DOCTYPE html>
<html>
<head><title>게시판</title></head>
<body>
  <h1>게시글 목록</h1>
  <% posts.forEach(post => { %>
    <div>
      <h3><%= post.title %></h3>
      <p><%= post.content %></p>
      <hr />
    </div>
  <% }); %>
</body>
</html>

 

1.4 index.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>홈페이지</title>
</head>
<body>
    <h2>환영합니다.</h2>
    <p>노현지의 홈페이지에 오신 걸 환영합니다.</p>

</body>
</html>

 

 

2. RESTful 

RESTful이란 웹 애플리케이션에서 리소스를 중심으로 설계된 API 방식으로, REST(Representational State Transfer) 아키텍처 스타일을 따르는 웹 서비스입니다. RESTful한 시스템은 URL을 통해 자원을 표현하고, HTTP 메서드(GET, POST, PUT, DELETE 등)를 통해 자원에 대한 행위를 명확하게 구분합니다. 예를 들어 /users는 사용자 목록이라는 자원을 의미하고, 여기에 GET 요청을 보내면 목록을 조회하고, POST는 새 사용자를 생성하며, /users/1에 PUT 요청을 보내면 1번 사용자를 수정하는 방식입니다. RESTful API는 구조가 직관적이고 일관성이 있어 클라이언트와 서버 간의 통신이 명확하고 유지보수에 용이합니다.

 

2.1 HTTP 메서드

const express = require("express");
const app = express();
const port = 3001;

app.use(express.json()); // 클라이언트 <-> 서버 간의 데이터를 json으로 처리

// 게시글 목록 조회
app.get("/posts", (req, res) => {
  res.send("모든 게시물 조회합니다.");
});

// 게시글 등록
app.post("/posts", (req, res) => {
  const { title, content } = req.body;
  res.send(`게시글 등록됨 ${title},${content}`);
});

// 게시글 하나 조회
app.get("/posts/:id", (req, res) => {
  res.send(`${req.params.id}번 게시글을 조회합니다.`);
});

// 게시글 수정
app.put("/posts/:id", (req, res) => {
  const { title, content } = req.body;
  res.send(`${req.params.id}번 게시글을 수정했습니다. (${title})`);
});

// 게시글 삭제
app.delete("/posts/:id", (req, res) => {
  res.send(`${req.params.id}번 게시글을 삭제했습니다.`);
});

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