[Javascript] HTTP 요청하기

winter100·2024년 1월 12일

자바스크립트

목록 보기
12/15

1. HTTP 요청하기

1.1 XMLHttpRequest 이용하기

1. 첫 번째 방법
  const xhr = new XMLHttpRequest(); // HTTP 요청을 보낼수 있는 객체 생성

  // 헤더가 필요할때쓰는 코드임. 헤더가 더 필요하다면 더 추가해서 쓸수있음.
  // 헤더가 추가되면 삭제는 불가능
  xhr.setRequestHeader("Content-Type","application/json");
  xhr.setRequestHeader("다른 헤더의 내용.....");
  xhr.setRequestHeader("다른 헤더의 내용.....");

  // ex) xhr.open('요청메서드','요청할 주소')
  xhr.open("GET", "https://jsonplaceholder.typicode.com/posts");

  xhr.responseType = "json"; // json 응답이 오면 자동으로 자바스크립트 객체로 변환해줌

 //onload로 받아온 데이터를 사용할 수 있음
  xhr.onload = function () {
    const listOfPosts = xhr.response; // .response에 데이터가 있음
    console.group(listOfPosts);
  };

  xhr.send(); // 요청을 보내는 메서드
-----------------------------------------------------
  2. 두 번째 방법
  const xhr = new XMLHttpRequest(); 

  xhr.open("GET", "https://jsonplaceholder.typicode.com/posts");

  xhr.onload = function () {
    // JSON.parse()는 JSON데이터를 자바스크립트로 바꿔주는 메서드
    // JSON.stringify()는 자바스크립트를 JSON데이터로 바꿔주는 메서드
    const listOfPosts = JSON.parse(xhr.response); 
    console.group(listOfPosts);
  };

  xhr.send();
-----------------------------------------------------
  3. 에러 관련
    const xhr = new XMLHttpRequest(); 

  xhr.open("GET", "https://jsonplaceholder.typicode.com/posts");

  xhr.onload = function () {
    if(xhr.status >=200 && xhr.status <300){
    const listOfPosts = JSON.parse(xhr.response); 
    console.group(listOfPosts);
    } else {
    reject(new Error("서버쪽 에러가 나면 이쪽이 활성화됨"));
    }

  };

// 에러를 잡아주긴 하지만 서버쪽 에러가 아닌 요청을 아예 보내지 못했거나 했을때 잡아줌.
  xhr.onerror = function () { 
    reject(new Error("인터넷이 연결 안되었거나 했을때만 이곳이 활성화됨"))
  };
  xhr.send();

1.2 XMLHttpRequest로 POST요청 보내기

  const xhr = new XMLHttpRequest();

  xhr.open("POST", "https://jsonplaceholder.typicode.com/posts");

  const data = {
    title: 'foo',
    body: 'bar',
    userId: 1,
  }

  const jsonData = JSON.stringify(data); //stringify로 JSON으로 바꿔서 보냄

  xhr.send(jsonData); // 네트워크 탭을 확인해보면 잘 전송되었음.

2. fetch api 이용해서 요청보내기

  • 현재 많이 사용하는 방식임.
'fetch API로 GET요청 보내기'
 const data = fetch("https://jsonplaceholder.typicode.com/posts").then(response=> return response.json())
 
 'fetch API에서는 JSON.parse()를 사용하는게 아닌 .json()을 사용함'
  • .json() 메소드는 Fetch API의 Response 객체에 되어있음. 이 메소드는 HTTP 응답 본문을 JSON으로 해석하고, 이를 JavaScript 객체로 변환한 Promise를 반환함
  • 반면에, JSON.parse() 메소드는 JSON 문자열을 파싱하여 JavaScript 값이나 객체를 동기적으로 생성함. 이 메소드는 JSON 형식의 문자열이 필요하며, 이 문자열을 JavaScript 객체로 변환함.

2.1 fetch API로 POST 요청내기

const option = {
      method: "POST", // 또는 'PUT' 등
      headers: {
        "Content-Type": "application/json",
      },
      body: JSON.stringify(data),
}
 const data = fetch("POST를 보낼 URL...", option)

3. formData 형식 알아보기

  • GET요청을 제외한 요청 메서드는 대부분 json형식을 취하긴 하지만 다른 형식을 취할수도 있음
  • 이미지나 파일을 보낼때 headers는 다른게 될수도 있음. (서버에 따라 다름)
  • 이때 사용할 수 있는 formData임
'1. HTML 코드'
    <div>
      <form id="formElem">
        <label>이름</label>
        <input type="text" name="name" />

        <label>나이</label>
        <input type="number" name="age" />

        <button type="submit">보내기</button>
      </form>
    </div>

'2. 자바스크립트 코드'
  const submitHandler = (event) => {
    event.preventDefault();

    const form = document.querySelector("form");
    
    
    '데이터 추가방법'
    '1. form 안의 input 태그의 name이 key값이 되고 value 값이 자동으로 들어감'
    const formData = new FormData(form);
    ------------------------
    '2. 이방법도 가능함'
    'formData.append('name', name의 input 값을 갖고있는 변수)'
    'formData.append('age', age의 input 값을 갖고있는 변수)'
    '1번이나 2번을 사용해 값을 추가 가능'
    ------------------------
    
    console.log(formData) // 이건 실행해도 데이터 안나옴. 브라우저가 보안을 위해 차단함

    // 하지만 아래의 for문 을 이용하면 값을 볼 수 있음.
    for (const key of formData.keys()) {
      console.log(key);
    }
    for (const value of formData.values()) {
      console.log(value);
    }

    fetch('API주소....',{
      method:"POST",
      body: formData, // FormData면 브라우저가 자동으로 headers를 설정해줌 개인적으로 설정해서 사용해도됨.
    })
  };

  const button = document.querySelector('button');
  button.addEventListener('click', submitHandler)

0개의 댓글