inflearn logo
강의

Course

Instructor

A Full-Stack Restaurant Guide Project for Non-Majors!: Front, Back-end, and Deployment

error: readStudents Query error

311

ipari

37 asked

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);
};

github javascript mysql HTML/CSS rest-api git aws

Answer 2

0

Jay

안녕하세요.

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

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

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

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

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

0

ipari

강사님. 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;
  }
};

live server가 안 떠요..

0

77

1

카카오맵 API 가 안뜹니다...

0

663

2

카카오맵API 지도 관련

0

169

1

Putty에서 nginx를 vi로 수정할때 오류

0

277

3

mysql과 선생님의 깃허브 코드연결

0

182

1

nodemon 실행오류

0

226

2

Azure 서버로 구축하고 작업하는 방법 알 수 있을까요?

0

254

2

css 적용 중 강의대로 적용되지 않아 질문 드립니다

0

346

2

강의를 잘 활용하는 법 추천 부탁드립니다.

0

282

1

MysqlWorkbench 접속문제

0

299

1

전체 핀이 조회되지 않습니다.

0

257

1

빅데이터 처리관련

1

279

1

섹션5의 2번째 강의 질문-setMap 비동기 처리 이유

0

233

1

PM2 EADDRINUSE 에러

0

403

2

인스턴스 중단 후 재시작

0

277

1

이미지 부분에 cctv 영상을 넣고 싶은데요.

0

580

2

노션 링크가 어디있나요 ?

1

307

1

axios 이후 마커 오류

0

289

0

service nginx restart 에러

0

709

1

섹션10 배포하기 unbuntu에서 root경로가 안뜹니다ㅠㅠ

0

497

3

선생님 추가적으로 새로운 페이지를 만드려고 하는데요...

0

244

1

코드 질문 드립니다!

0

223

1

혹시 강의자료 노션 내리셨나요?

0

234

1

노드몬 에러 참조하세요

0

355

1