Notice
Recent Posts
Recent Comments
Link
«   2025/05   »
1 2 3
4 5 6 7 8 9 10
11 12 13 14 15 16 17
18 19 20 21 22 23 24
25 26 27 28 29 30 31
Archives
Today
Total
관리 메뉴

사고쳤어요

[Node.js] 유튜브 서비스 - 채널 조회 서비스(DB 연결) 본문

웹 풀스택

[Node.js] 유튜브 서비스 - 채널 조회 서비스(DB 연결)

kevinmj12 2025. 2. 26. 21:45

https://makeaccident.tistory.com/123

 

[Node.js] 유튜브 서비스 - 채널 생성, 채널 조회(POST, GET)

채널 생성const express = require("express");const app = express();app.listen(3000);app.use(express.json());let channelDb = new Map();var id = 1;app .route("/channels") // 채널 전체 조회 .get((req, res) => {}) // 채널 생성 .post((req, res) =>

makeaccident.tistory.com

채널 조회 서비스를 데이터베이스에 연결하여 구현해보자.

 

채널 개별 조회

// 채널 개별 조회
  .get((req, res) => {
    let { id } = req.params;
    id = parseInt(id);

    let sql = `SELECT * FROM channels WHERE id=?`;
    conn.query(sql, id, (err, rows, fields) => {
      if (err instanceof Error) {
        console.log(err);
        return;
      }

      let channel = rows[0];
      if (channel) {
        res.json({
          channel,
        });
      } else {
        res.status(404).json({
          message: "요청이 올바르지 않습니다.",
        });
      }
    });
  })

 

채널 전체 조회

// 채널 전체 조회
  .get((req, res) => {
    var { userId } = req.body;
    var channels = [];

    if (!userId) {
      res.status(404).json({
        message: "userId가 포함되어있지 않습니다.",
      });
    } else {
      let sql = `SELECT * FROM channels WHERE user_id=?`;
      conn.query(sql, userId, (err, rows, fields) => {
        if (err instanceof Error) {
          console.log(err);
          return;
        }

        if (rows.length) {
          res.json({
            rows,
          });
        } else {
          res.status(404).json({
            message: "조회할 채널이 없습니다.",
          });
        }
      });
    }
  })