유동

[Express] Cannot read properties of undefined 본문

node.js/ExpressJS

[Express] Cannot read properties of undefined

동 선 2023. 7. 18. 21:57

일단 해당 에러는 자바스크립트로 개발하는 분들은 매우많이 접했을 에러 일 것이다.

undefined가 할당되어있는 변수에 접근하였을 경우 해당 에러가 발생한다.

 

(POST방식) 로그인api 요청에서 아이디, 비밀번호를 Body로 보내주는 코드 , 대략적인 흐름은

 

1. 아이디 패스워드를 받아 destructuring 해줌

  const { loginId, password } = req.body;

2. 해당 값들의 유효성을 검증하기 위해 커스텀으로 만든 exception모듈로 검사해준다

https://inko51366.tistory.com/34

- 만약 여기서 하나라도 통과하지 못할 시 Error객체를 던져줌, 해당 에러는 에러 처리 미들웨어로 가서 프론트에게 에러를 반환함

(에러처리 미들웨어는 나중에 다룰것임) ㄱㄷ

exception(loginId, "loginId").checkInput().checkLength(1, maxLoginIdLength);
exception(password, "password").checkInput().checkLength(1, maxPwLength);

3. 나머지 작업들 처리 (DB연결, JWT 발급, 등등)

 

postman으로 테스트 해봅시다

정상적으로 로그인요청하였을 경우 (401 Unauthorized error)

정상이네요

 

비정상적으로 요청한경우 (400error가 나와야되는데 500 error가 뜬다)

id로 보내줘야되는데 Id 로 보내줌. 에러나야댐

 

위와같이 500 에러로 뜨며 아래와 같은 에러가 터미널에 찍힌다 (Cannot read properties of undefined 에러)

TypeError: Cannot read properties of undefined (reading 'length')
at Exception.checkLength (/home/ubuntu/node/src/module/exception.js:15:15)
at /home/ubuntu/node/src/router/account.js:20:48
at Layer.handle [as handle_request] (/home/ubuntu/node/node_modules/express/lib/router/layer.js:95:5)
at next (/home/ubuntu/node/node_modules/express/lib/router/route.js:144:13)
at Route.dispatch (/home/ubuntu/node/node_modules/express/lib/router/route.js:114:3)
at Layer.handle [as handle_request] (/home/ubuntu/node/node_modules/express/lib/router/layer.js:95:5)
at /home/ubuntu/node/node_modules/express/lib/router/index.js:284:15
at Function.process_params (/home/ubuntu/node/node_modules/express/lib/router/index.js:346:12)
at next (/home/ubuntu/node/node_modules/express/lib/router/index.js:280:10)
at Function.handle (/home/ubuntu/node/node_modules/express/lib/router/index.js:175:3)

exception모듈로 넘어간 input값(loginId)이 undefined였던 것.

 

account.js 코드

const { loginId, password } = req.body;
exception(loginId, "loginId").checkInput().checkLength(1, maxLoginIdLength);

exception.js 코드

function Exception(input, name) {
  this.checkInput = () => {
    if (typeof input === undefined || input === "") {
      const error = Error(`(${name}): 값이 비어있습니다`);
      error.status = 400;

      throw error;
    }
    return this;
  }

    this.checkLength = (min, max) => {
    // 해당 부분에서 Cannot read properties of undefined (reading 'length') 발생
    if (input.length < min || input.length > max) {
      const error = Error(`(${name}): 길이가 비정상적입니다`);
      error.status = 400;

      throw error;
    }
    return this;
  }

  this.checkIdRegex = () => {
    if (!loginIdRegex.test(input)) {
      const error = Error(`(${name}): 정규표현식 실패`);
      error.status = 400;

      throw error;
    }
    return this;
  }

    ....
}

원인 1

  • destructure로 받은 loginId 변수에 담기지 않은 채로(undefined) exception 모듈의 매개변수로 넘어갔기 때문, 당연히 undefined를 읽으려 하니 에러가 생긴다.

원인 2

  • Exception 함수의 checkInput 메소드에서
typeof input === undefined // ← 실수로 따옴표 안붙여서 그냥 해당 로직을 그냥 지나쳤음

해결

  • typeof를 사용해서 검사하려면 typeof input === “undefined” 아니면 input === undefined 해야댐
  this.checkInput = () => {
    if (input === undefined) {
      const error = Error(`(${name}): 요청값을 확인해주세요`);
      error.status = 400;

      throw error;
    }
    return this;
  }

해결완료

 

어처구니없게 이런 기본적인 에러가지고 3시간정도를 소비했다.. 하지만 이를 통해 프로그램의 흐름을 재정돈하며 에러를 찾는 방법도 배웠음