• 카테고리

    질문 & 답변
  • 세부 분야

    풀스택

  • 해결 여부

    미해결

error: readStudents Query error

22.10.17 21:46 작성 조회수 180

0

- 학습 관련 질문을 남겨주세요. 상세히 작성하면 더 좋아요!
- 먼저 유사한 질문이 있었는지 검색해보세요.
- 서로 예의를 지키며 존중하는 문화를 만들어가요.
- 잠깐! 인프런 서비스 운영 관련 문의는 1:1 문의하기를 이용해주세요.

 

postman에서 get 메서드로 http://localhost:3000/students 실행했을 때 뜨지 않고, vscode console에서는 error: readStudents Query error라고 뜹니다.

readStudents query가 잘못되서 전체학생 목록이 안나오는 것 같습니다. 어디가 잘못 됐을까요?

<indexcontroller>

const { pool } = require("../../config/database");
const { logger } = require("../../config/winston");
const jwt = require("jsonwebtoken");
const secret = require("../../config/secret");

const indexDao = require("../dao/indexDao");

//학생 생성
exports.createStudent = async function(req,res) {
  const { studentName, major, birth, address} = req.body;

  console.log(studentName, major, birth, address)
};
//학생테이블 조회
exports.readStudents = async function(req, res){

  const { studentIdx } = req.params;

  try {
    const connection = await pool.getConnection(async (conn) => conn);
    try {
      const [rows] = await indexDao.selectStudents(connection,studentIdx);
    

      return res.send({
        result: rows,
        isSuccess: true,
        code: 200, // 요청 실패시 400번대 코드
        message: "요청 성공",
      });
    } catch (err) {
      logger.error(`readStudents Query error\n: ${JSON.stringify(err)}`);
      return false;
    } finally {
      connection.release();
    }
  } catch (err) {
    logger.error(`readStudents DB Connection error\n: ${JSON.stringify(err)}`);
    return false;
  }
};

// 예시 코드
exports.example = async function (req, res) {
  try {
    const connection = await pool.getConnection(async (conn) => conn);
    try {
      const [rows] = await indexDao.exampleDao(connection);

      return res.send({
        result: rows,
        isSuccess: true,
        code: 200, // 요청 실패시 400번대 코드
        message: "요청 성공",
      });
    } catch (err) {
      logger.error(`example Query error\n: ${JSON.stringify(err)}`);
      return false;
    } finally {
      connection.release();
    }
  } catch (err) {
    logger.error(`example DB Connection error\n: ${JSON.stringify(err)}`);
    return false;
  }
};



<Indexdao 부분>
const { pool } = require("../../config/database");
exports.selectStudents = async function (connection, studentIdx) {
  const Query = `SELECT * FROM Students where studentIdx = ?;`;
  const Params = [studentIdx];

  const rows = await connection.query(Query, Params);

  return rows;
};

exports.exampleDao = async function (connection) {
  const Query = `SELECT * FROM Students;`;
  const Params = [];

  const rows = await connection.query(Query, Params);

  return rows;
};



<IndexRoute 부분>
module.exports = function (app) {
  const index = require("../controllers/indexController");
  const jwtMiddleware = require("../../config/jwtMiddleware");

  // // 라우터 정의
  // // app.HTTP메서드(uri, 컨트롤러 콜백함수)
  // app.get("/dummy", index.example);

  //학생테이블 조회
  app.get("/students/:studentIdx", index.readStudents);
  app.post("/students", index.createStudent);
};

답변 2

·

답변을 작성해보세요.

0

안녕하세요.

아래 깃 레포에서 전체 코드 확인하실 수 있습니다.

https://github.com/mmvv11/food-map-dist-example

쿼리 에러 나는 것 봐선 dao 쪽 잘봐야할 것 같은데요,

쿼리는 제가 보기에도 이상은 없는 것 같고,,

DB 테이블명, DB 연결 상태, secret 등 설정을 확인해보셔야 할 것 같습니다

0

신영현님의 프로필

신영현

질문자

2022.10.18

강사님. indexController 완성코드 좀 올려주세요... (학생테이블 관련된거요..) 제가 뭔가 잘못 하고 있는 것 같아요...

const { pool } = require("../../config/database");
const { logger } = require("../../config/winston");
const jwt = require("jsonwebtoken");
const secret = require("../../config/secret");

const indexDao = require("../dao/indexDao");
//학생 업데이트
exports.updateStudent = async function (req,res){
  const { studentName, major, birth, address } = req.body;
  const { studentIdx } = req.params;

  if (studentName && typeof studentName !== "string") {
    return res.send({
      isSuccess: false, 
      code:400, //요청실패시 400번대 코드
      message: "값을 정확히 입력해주세요.",
    });
  }
  if (major && typeof major !== "string") {
    return res.send({
      isSuccess: false, 
      code:400, //요청실패시 400번대 코드
      message: "값을 정확히 입력해주세요.",
    });
  }
  if (address && typeof address !== "string") {
    return res.send({
      isSuccess: false, 
      code:400, //요청실패시 400번대 코드
      message: "값을 정확히 입력해주세요.",
    });
  }

  //birth : YYYY-MM-DD 형식 검사
  var regex = RegExp(/^\d{4}\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])$/);
  regex.test("2020/09/25");
  if (birth && !regex.test(birth)) {
    return res.send({
      isSuccess: false, 
      code:400, //요청실패시 400번대 코드
      message: "날짜형식을 확인해주세요.",
    });
  }
  return;

  try {
    const connection = await pool.getConnection(async (conn) => conn);
    try {
      const isValidStudentIdx = await indexDao.isValidStudentIdx(studentIdx)
      if (!isValidStudentIdx) {
        return res.send({
          result: rows,
          isSuccess: false,
          code: 410, // 요청 실패시 400번대 코드
          message: "유효한 학생 인덱스가 아닙니다.",
        });
      }
      const [rows] = await indexDao.updateStudents(studentIdx, connection,studentName, major, birth, address);
    

      return res.send({
        result: rows,
        isSuccess: true,
        code: 200, // 요청 실패시 400번대 코드
        message: "학생 수정 성공",
      });
    } catch (err) {
      logger.error(`updateStudents Query error\n: ${JSON.stringify(err)}`);
      return false;
    } finally {
      connection.release();
    }
  } catch (err) {
    logger.error(`updateStudents DB Connection error\n: ${JSON.stringify(err)}`);
    return false;
  }
};
//학생테이블 조회
exports.selectStudents = async function(req, res){

  const { studentIdx } = req.params;

  try {
    const connection = await pool.getConnection(async (conn) => conn);
    try {
      const [rows] = await indexDao.selectStudents(connection,studentIdx);
    
      return res.send({
        result: rows,
        isSuccess: true,
        code: 200, // 요청 실패시 400번대 코드
        message: "요청 성공",
      });
    } catch (err) {
      logger.error(`selectStudents Query error\n: ${JSON.stringify(err)}`);
      return false;
    } finally {
      connection.release();
    }
  } catch (err) {
    logger.error(`selectStudents DB Connection error\n: ${JSON.stringify(err)}`);
    return false;
  }
}
//학생 생성
exports.createStudent = async function(req,res) {
  const { studentName, major, birth, address } = req.body;

  console.log(studentName, major, birth, address);
  // studentName, major, address:문자열
  if (
    typeof studentName !== "string" ||
    typeof major !== "string" ||
    typeof address !== "string"
  ) {
    return res.send({
      isSuccess: false, 
      code:400, //요청실패시 400번대 코드
      message: "값을 정확히 입력해주세요.",
    });
  }
  //birth : YYYY-MM-DD 형식 검사
  var regex = RegExp(/^\d{4}\/(0[1-9]|1[012])\/(0[1-9]|[12][0-9]|3[01])$/);
  regex.test("2020/09/25");
  if (!regex.test(birth)) {
    return res.send({
      isSuccess: false, 
      code:400, //요청실패시 400번대 코드
      message: "날짜형식을 확인해주세요.",
    });
  }
  try {
    const connection = await pool.getConnection(async (conn) => conn);
    try {
      const [rows] = await indexDao.insertStudents(connection,studentName, major, birth, address);
    

      return res.send({
        result: rows,
        isSuccess: true,
        code: 200, // 요청 실패시 400번대 코드
        message: "학생 생성 성공",
      });
    } catch (err) {
      logger.error(`createStudent Query error\n: ${JSON.stringify(err)}`);
      return false;
    } finally {
      connection.release();
    }
  } catch (err) {
    logger.error(`createStudent DB Connection error\n: ${JSON.stringify(err)}`);
    return false;
  }
};
//학생테이블 조회
exports.readStudents = async function(req, res){

  const { studentIdx } = req.params;

  try {
    const connection = await pool.getConnection(async (conn) => conn);
    try {
      const [rows] = await indexDao.readStudents(connection,studentIdx);
    

      return res.send({
        result: rows,
        isSuccess: true,
        code: 200, // 요청 실패시 400번대 코드
        message: "요청 성공",
      });
    } catch (err) {
      logger.error(`readStudents Query error\n: ${JSON.stringify(err)}`);
      return false;
    } finally {
      connection.release();
    }
  } catch (err) {
    logger.error(`readStudents DB Connection error\n: ${JSON.stringify(err)}`);
    return false;
  }
};