ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • Node.js와 Express를 사용한 RESTful API 개발 및 MySQL 연동
    Express 2024. 3. 15. 13:02

    API 개발을 시작하기 위해 Node.js와 Express를 사용하여 백엔드 서버를 설정하고, MySQL 데이터베이스와 연동하는 기본적인 절차를 정리해 보았습니다.

    Node.js와 Express를 사용한 RESTful API 개발 및 MySQL 연동

    이 과정은 사용자 인증, 포스트 생성, 조회, 수정, 삭제 등의 기능을 위한 RESTful API 개발의 기초 과정입니다.

     

    Step 1: Express 서버 설정

    Express 앱 생성

    // backend/index.js
    const express = require('express');
    const app = express();
    const PORT = process.env.PORT || 3001;
    
    
    app.use(express.json());
    
    
    app.get('/', (req, res) => {
      res.send('Hello World!');
    });
    
    
    app.listen(PORT, () => {
      console.log(`Server is running on port ${PORT}`);
    });

     

    서버 실행

    node index.js

    브라우저에서 http://localhost:3001/로 접속해 "Hello World!" 메시지를 확인합니다.

     

    Step 2: MySQL 데이터베이스 연결

     

    MySQL 연결 설정

    mysql 라이브러리를 설치합니다.

    npm install mysql

    MySQL 데이터베이스에 연결합니다.

    // backend/database.js
    const mysql = require('mysql');
    
    
    const db = mysql.createConnection({
      host: "your_host",
      user: "your_username",
      password: "your_password",
      database: "your_database"
    });
    
    
    db.connect((err) => {
      if (err) throw err;
      console.log("Connected to MySQL");
    });
    
    
    module.exports = db;

     

    Step 3: API 라우팅 및 CRUD 연산

    라우팅 설정

    express.Router()를 사용하여 라우트를 모듈화합니다.

    // backend/routes/posts.js
    const express = require('express');
    const router = express.Router();
    const db = require('../database');
    
    
    // 포스트 목록 조회
    router.get('/posts', (req, res) => {
      // SQL 쿼리 실행
    });
    
    
    // 포스트 생성
    router.post('/posts', (req, res) => {
      // SQL 쿼리 실행
    });
    
    
    // 포스트 수정
    router.put('/posts/:id', (req, res) => {
      // SQL 쿼리 실행
    });
    
    
    // 포스트 삭제
    router.delete('/posts/:id', (req, res) => {
      // SQL 쿼리 실행
    });
    
    
    module.exports = router;

     

    라우트를 Express 앱에 등록

    // backend/index.js에 추가
    const postsRoutes = require('./routes/posts');
    app.use('/api', postsRoutes);

     

    CRUD 연산 구현

     

    각 라우트에서 필요한 SQL 쿼리를 실행하여 CRUD 연산을 구현합니다.

    예를 들어, 포스트 목록 조회, 포스트 생성, 수정, 삭제 등의 기능을 아래와 같이 구현할 수 있습니다.

     

    포스트 목록 조회

    router.get('/posts', (req, res) => {
      const sqlQuery = "SELECT * FROM posts";
      db.query(sqlQuery, (err, results) => {
        if (err) throw err;
        res.json(results);
      });
    });

     

    포스트 생성

    router.post('/posts', (req, res) => {
      const postData = req.body;
      const sqlQuery = "INSERT INTO posts SET ?";
      db.query(sqlQuery, postData, (err, result) => {
        if (err) throw err;
        res.json({ message: "Post created", postId: result.insertId });
      });
    });

     

    포스트 수정

    router.put('/posts/:id', (req, res) => {
      const { id } = req.params;
      const updatedData = req.body;
      const sqlQuery = "UPDATE posts SET ? WHERE id = ?";
      db.query(sqlQuery, [updatedData, id], (err, result) => {
        if (err) throw err;
        res.json({ message: "Post updated" });
      });
    });

     

    포스트 삭제

    router.delete('/posts/:id', (req, res) => {
      const { id } = req.params;
      const sqlQuery = "DELETE FROM posts WHERE id = ?";
      db.query(sqlQuery, id, (err, result) => {
        if (err) throw err;
        res.json({ message: "Post deleted" });
      });
    });

    Step 4: 테스트

    API를 테스트하기 위해, Postman이나 curl을 사용하여 생성된 각 엔드포인트에 대한 요청을 보내고, 응답을 확인합니다. 각 API 엔드포인트의 정상 작동을 확인함으로써, 사용자 인터페이스 또는 다른 애플리케이션과의 통합 준비를 마칩니다.

    • 예제 curl 요청:

    포스트 생성:

    curl -X POST -H "Content-Type: application/json" -d '{"title":"새 포스트", "content":"포스트 내용"}' http://localhost:3001/api/posts

     

    포스트 조회:

    curl http://localhost:3001/api/posts

     

    이 가이드를 통해, Node.js와 Express를 사용하여 MySQL 데이터베이스를 연동하는 RESTful API의 기본 구조를 성공적으로 구축하고 테스트할 수 있습니다. 추가적으로, 사용자 인증이나 복잡한 로직을 필요로 하는 기능을 API에 통합하여 확장할 수 있습니다.

     

    google apps 스크립트 프로젝트에서 구글 드라이브 API를 활성화하는 방법에 대해서 알아보기

    Pretty Button 방법 보기

     

    'Express' 카테고리의 다른 글

    Express.js로 간단한 웹 서버 구축하기  (0) 2024.03.15
Designed by Tistory.