Asynchronous JavaScript And XML, 서버와 비동기적으로 데이터 주고 받는 자바스크립트 기술
서버란 무엇인지에 대해 이해하고 있어야 한다. 서버란, 데이터를 요구하면 데이터를 보내주는 프로그램이다.
ex) 네이버 웹툰 서버 : 유저가 웹툰을 달라고 요구하면 웹툰을 보내주는 프로그램이다.
서버한테 데이터를 달라고 할 때는 정해진 방법이 있다.
1. 원하는 데이터 URL
2. 그 URK로 GET 요청
function reqListener () {
console.log(this.responseText);
}
var oReq = new XMLHttpRequest();
oReq.addEventListener("load", reqListener);
oReq.open("GET", "http://www.example.org/example.txt");
oReq.send();
fetch('http://example.com/movies.json')
.then(function(response) {
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
});
fetch('http://example.com/movies.json')
.then(function(response) {
if(!response.ok) {
throw new Error('400 아니면 500 에러남')
return response.json();
})
.then(function(myJson) {
console.log(JSON.stringify(myJson));
})
.catch(() => {
console.log('에러남')
})
$.ajax()
// Want to use async/await? Add the `async` keyword to your outer function/method.
async function getUser() {
try {
const response = await axios.get('/user?ID=12345');
console.log(response);
} catch (error) {
console.error(error);
}
ajax 요청 시 CORS 관련 에러를 자주 보게 된다. naver.com -> kakao.com 으로 ajax 요청이 불가능하다. 보안 이슈 중 하나이다.
이 기능을 끄고 싶을 때는 헤더에
Access-Control-Allow-Origin : "*" 를 추가하거나 CORS 정책 관련 기능을 끄면 된다.
https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
https://www.youtube.com/watch?v=nKD1atl6cAw&t=11s
https://developer.mozilla.org/ko/docs/Web/API/Fetch_API/Using_Fetch
https://tuhbm.github.io/2019/03/21/axios/
https://github.com/axios/axios