const xhr = new XMLHttpRequest();
// xhr을 불러와서 상태를 통해서 처리함
xhr.onreadystatechange = function() {
if (xhr.readyState === xhr.DONE) {
if (xhr.status === 200) {
console.log(xhr.response)
} else {
console.error('error')
}
}
}
// 요청을 해서 요청 결과를 send를 통해 호출해 받아와서 처리할 수 있음
xhr.open('GET', 'https://jsonplaceholder.typicode.com/todos/1');
xhr.send();
// url을 넣고 then 체이닝을 통해서 결과 처리를 함 .json으로 json 객체로 변환하고 처리함
// 1. URL fetch 요청
// 2. Fetch 응답 객체를 받아옴
// 3. 응답 객체가 JSON => 순수 JS 객체로 변환(그래서 객체로써 활용하고 다루기 용이해짐)
fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => response.json())
.then((json) => console.log(json));
fetch('URL', {
method: 'POST',
headers: [
Cookie: '',
},
body: {
name: '',
}
});
fetch('URL')
.then(async(response) => {
const data = await response.json();
// 결과 데이터 활용
});
Response {
status: 200,
ok: true
}
Method의 경우 대표적으로 GET, POST, PUT, DELETE가 있음, 각각 예시로 사이트 불러오기, 게시물 생성, 게시물 수정, 게시물 삭제 등의 기능으로 활용할 수 있음
여기서 추가로 CORS 정책도 알아야함 CORS 정책이란 다른 도메인의 사이트에 요청을 보낼 때, 미리 허용된 호스트가 아니라면 요청을 거부하는 정책임
그래서 허용된 호스트가 아니면 CORS Error가 나타나고, 맞다면 응답 헤더 Access-Control-Allow-Origin과 함께 정상 응답을 냄
JSON.stringify
를 통해서 일반적인 JavaScript 객체를 JSON으로 변환할 수 있음(JSON 객체는 문자열로 type을 받아들임)JSON.parse
를 통해서 JavaScript 객체로 바꿀 수 있음// json 타입 예시
{
"squadName": "Super hero squad",
"homeTown": "Metro City",
"formed": 2016,
"secretBase": "Super tower",
"active": true,
"members": [
{
"name": "Molecule Man",
"age": 29,
"secretIdentity": "Dan Jukes",
"powers": ["Radiation resistance", "Turning tiny", "Radiation blast"]
},
{
"name": "Madame Uppercut",
"age": 39,
"secretIdentity": "Jane Wilson",
"powers": [
"Million tonne punch",
"Damage resistance",
"Superhuman reflexes"
]
},
{
"name": "Eternal Flame",
"age": 1000000,
"secretIdentity": "Unknown",
"powers": [
"Immortality",
"Heat Immunity",
"Inferno",
"Teleportation",
"Interdimensional travel"
]
}
]
}