프로그래밍 공부방

[node.js] httprequest 후 서버에서 request할 때 undefined 에러 해결방법 본문

백엔드/Node.js

[node.js] httprequest 후 서버에서 request할 때 undefined 에러 해결방법

김갱갱 2022. 7. 26. 22:44

클라이언트 측에서 httpRequest를 서버로 보낸 후 서버에서 request를 하려고 하는데 문제가 생겼습니다.

왜 문제가 생겼을까요? 코드는 아래와 같습니다.

/* signup.js 클라이언트 코드*/ 

signup_btn.addEventListener("click", function(e) {
  if(pw.value && pw.value === pw_check.value){ // pw값과 pw체크값이 같다면
    if (id.value == ''){ // id 값이 비어있다면 
      alert("아이디를 입력하세요");
    } else { // id값이 비어있지 않다면
      makeRequest('http://localhost:5000/signup/process', id.value, pw.value); 
    }    
  }else{ // pw값과 pw체크값이 불일치할 때
    alert("비밀번호가 서로 일치하지 않습니다");
  }
});

var httpRequest;

/* 서버로 요청할 때 */
function makeRequest(url, id, pw) {
  httpRequest = new XMLHttpRequest();

  if (!httpRequest) {
    alert('XMLHTTP 인스턴스 생성 오류');
    return false;
  }

  var data = {'id': id, 'pw': pw};
  data = JSON.stringify(data);

  httpRequest.onreadystatechange = alertContents;
  httpRequest.open('POST', url, true);
  httpRequest.setRequestHeader('Content-Type', 'application/json');
  httpRequest.send(data); // json형태로 데이터 보내기
  }

  /* 서버에서 요청에 성공했을 때 */
  function alertContents() { //
    if (httpRequest.readyState === XMLHttpRequest.DONE) {
      if (httpRequest.status === 200) { //서버에서 요청에 성공했을 때
        alert("회원가입이 완료되었습니다");
        location.href = "/login";
      } else {
        alert('request에 문제가 있습니다');
      }
    }
  }
/* signup.js 서버쪽 코드*/

router.post('/process', function(req, res){
	console.log(req.body);
}

 

이 코드로 진행했을 때 console.log(req.body)의 결과값은 undefined가 떴습니다.

undefined란 무엇일까요? undefined는 아직 값이 할당되지 않은 값을 말합니다.

따라서 req.body의 값이 할당되지 않았다는 뜻입니다.

이를 해결하기 위해서는 클라이언트에서 보낸 body를 parsing 해주어야 합니다.

 

body parsing하는 방법

/* json 형태로 parsing */
router.use(express.json());

이 코드를 post나 get 등으로 요청을 받아들이기 전에 넣어줍니다.

이 코드는 json 형태로 body를 parsing한다는 뜻입니다.

 

위 코드를 추가한 후에는 undefined가 아닌 제대로 된 값이 나오는 것을 확인할 수 있습니다.

 

만약에 json 형태가 아닌 x-www-form-urlencoded 형태로 body를 parsing하고 싶다면 urlencoded를 사용해주세요~

/* x-www-form-urlencoded 형태로 parsing */
router.use(bodyParser.urlencoded({extended:true}));