• [JS] Fetch()로 formdata post 요청하기

    2023. 4. 16.

    by. 지은이: 김지은

    728x90

     

    이전글 - [JS] 자바스크립트에 Fetch() 함수로 HTTP 요청하기

     

     

    로그인 폼을 만들었다고 했을 때 입력된 값을 백엔드 서버로 전송 시 JSON 형태로 데이터를 전송하려고 한다.

    // index.html
    
    <div class="form">
          <label class="label" for="emailInput">이메일</label>
          <input class="input" id="emailInput" type="email" placeholder="abc@gmail.com"/>
          <label class="label" for="passwordInput">비밀번호</label>
          <input class="input" id="passwordInput" type="password" />
          
          <button id="submitButton">로그인</button>
    </div>

    label의 for과 input의 id를 일치시키면 한 세트로 만들 수 있다.

    이제 로그인 버튼을 눌렀을 때 비밀번호가 일치하는지 아닌지 alert창을 띄우는 코드를 작성하려고 한다.

     

    // index.js
    
    const emailInput = document.querySelector("#emailInput");
    const passwordInput = document.querySelector("#passwordInput");
    const submitButton = document.querySelector("#submitButton");

    요소 가져오기

     

    submitButton.addEventListener("click", login); // 로그인 버튼 클릭 시 이벤트 핸들러 실행
    
    async function login(e) {
      e.preventDefault(); // 버튼 클릭 시 새로고침 되는 걸 방지
      
      // input의 email, password 값을 가져와서 아무 값도 입력하지 않으면 alert 창 띄우기
      const email = emailInput.value;
      const password = passwordInput.value;
    
      if (!email) {
        alert("이메일을 입력해 주세요.");
        return; // 함수 종료
      }
    
      if (!password) {
        alert("비밀번호를 입력해 주세요.");
        return; // 함수 종료
      }
    }

     

    input에 아무것도 입력하지 않고 버튼을 클릭하면 alert 경고창이 뜨게 만들었다.

     

     

    이제 이메일, 비밀번호를 입력한 폼에 Fetch api로 POST 요청을 보내려고 한다.

    async function login(e) {
        ...
        
        // 입력한 email, password 값으로 객체로 만들기
        const data = {
            email,
            password,
        };
    
        const res = await fetch('API url', {
            method: "POST",
            headers: {
                "Content-Type": "application/json",
                },
            body: JSON.stringify(data), //  데이터를 JSON 형태로 감싸주기
        });
    }

     

    fetch() 함수의 첫번째 인자로 서버에 보낼 api 주소를 전달해주고, 두번째 인자에 객체 형태로 데이터의 옵션을 전달한다.

    body에는 객체로 만든 data를 JSON 문자열로 변환해서 전달한다.

     

    async function login(e) {
    	...
        if (res.status === 200) {
            alert('로그인에 성공하였습니다!');
        } else {
            alert('로그인에 실패하였습니다...');
        }
    }

    마지막으로 POST 요청 시 응답코드가 200(2XX = 성공)이면 로그인 성공, 200이 아니면 로그인 실패 alert창을 띄운다.

     

    Reference

    • 엘리스

    댓글