Cannot set headers after they are sent to the client 에러 해결

아기코딩단2·2022년 11월 29일
0

개요 : 로그인 구현중 발생한 에러
원인 : for문을 돌면서 중복으로 db에 접근하게 되면 나타나는 에러로 보임

예제 코드

for (let i = 0; i < rows.length; i++) {
  if (req.body.id === rows[i].id && req.body.pwd === rows[i].pwd) {
    //console.log("ok");
    //console.log(rows[i].nickname);
    return res.status(200).json({
      code: 200,
      message: "성공",
      body: rows[i].nickname,
    });

for 문을 없애야함

connection.query(
      "select id, pwd, nickname from user where id=? and pwd=?",
      [req.body.id, req.body.pwd],
      (err, rows) => {
        if (rows.length === 0) {
          if (err) {
            throw err;
          }
          res.status(400).json({
            code: 400,
            message: "실패",
          });
        } else {
          res.status(200).json({
            code: 200,
            message: "성공",
            body: req.body.nickname,
          });
        }
      }
    );

추가 참고한 문서 :
https://avengersrhydon1121.tistory.com/150

https://bobbyhadz.com/blog/javascript-error-cannot-set-headers-after-they-are-sent-to-client

profile
레거시 학살자

0개의 댓글