1. HTTP 요청하기
1.1 XMLHttpRequest 이용하기
1. 첫 번째 방법
const xhr = new XMLHttpRequest();
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("다른 헤더의 내용.....");
xhr.setRequestHeader("다른 헤더의 내용.....");
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts");
xhr.responseType = "json";
xhr.onload = function () {
const listOfPosts = xhr.response;
console.group(listOfPosts);
};
xhr.send();
-----------------------------------------------------
2. 두 번째 방법
const xhr = new XMLHttpRequest();
xhr.open("GET", "https://jsonplaceholder.typicode.com/posts");
xhr.onload = function () {
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);
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",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(data),
}
const data = fetch("POST를 보낼 URL...", option)
- 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 (const key of formData.keys()) {
console.log(key);
}
for (const value of formData.values()) {
console.log(value);
}
fetch('API주소....',{
method:"POST",
body: formData,
})
};
const button = document.querySelector('button');
button.addEventListener('click', submitHandler)