
ajax (JQuery)
$.ajax({
url: "localhost:8080"
, type: "GET"
, dataType: "json"
, success: function (response) {
console.log("성공");
console.log("data: " + response);
}
, error: function (error) {
console.log("실패");
console.log(error);
}
});
$.ajax({
url: "localhost:8080"
, type: "GET"
, dataType: "json"
})
.done(function (response) {
console.log("성공");
console.log("data: " + response);
}
)
.fail(function (error) {
console.log("실패");
console.log(error);
}
)
// 템플릿
// ===== 옵션 스타일 =====
$.ajax({
url: '/api/users',
success: function() { }, // 성공
error: function() { }, // 실패
complete: function() { } // 항상
});
// ===== 체이닝 스타일 =====
$.ajax({ url: '/api/users' })
.done(function() { }) // 성공 (= success)
.fail(function() { }) // 실패 (= error)
.always(function() { }); // 항상 (= complete) 거의 반 사양된 코드, 무거운 JQuery 사용으로 지양됨
예전 브라우저 환경에 따라 JS 사용법이 달랐을 때
JQuery가 등장하며 나온 비동기 통신 라이브러리
fetch
async function fetchGetTest(url) {
try {
const fetchGetResponse = await fetch(url);
if(!fetchGetResponse.ok) {
throw new Error(`"통신 실패! ${fetchGetResponse.status}"`)
}
const fetchGetBody = await fetchGetResponse.json();
console.log(fetchGetBody);
} catch(error) {
console.log(error, error.message);
}
}
async function fetchPostTest() {
try {
const fetchPostTest = await fetch("https://jsonplaceholder.typicode.com/posts", {
method: 'POST',
headers: {
'Content-type': 'application/json'
},
body: JSON.stringify({
title: 'testTitle',
body: 'testBody',
userId: 1
})
});
if(!fetchTest.ok) {
throw new Error(`"TEST ERROR : ${fetchPostTest.status}"`)
}
const result = await fetchPostTest.json();
console.log(result);
} catch(error) {
console.log(error, error.message);
}
}JS 에 내장되어 있는 비동기 통신 함수
JSON 으로의 변환은 수동으로 꼭 선언해주어야함
fetchResponse.json(), 직렬화 부분 필수
axios
import axios from 'axios';
// CREATE -> axios는 따로 api 헤더를 만들 수 있음
const axiosHttpClient = axios.createaxios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
headers: {
'Content-Type': 'application/json',
'Authorization': auth token 명시
}
});
// GET API
async function axiosGetTest() {
try {
const response = await axios.get("https://jsonplaceholder.typicode.com/users");
// axiosHttpClient.get("/users);"
console.log(response);
} catch (error) {
console.log("error : ", error.message);
}
}
// POST API
async function axiosPOSTTest() {
try {
const response = await axios.post("https://jsonplaceholder.typicode.com/posts", {
title: 'testTitle',
body: 'testBody',
userId: 1
});
/* axiosHttpClient.post(/posts, {
title: 'testTitle',
body: 'testBody',
userId: 1
} */
console.log(response.data);
} catch (error) {
console.log("error : ", error.message);
}
}편의성이 높은 비동기 통신 방법 (공통 API 헤더를 위한 CREATE 및 각 HTTP 메서드 제공)
JSON 변환, 에러 처리 등을 자동으로 내포하고 있어 사용하기 편리함
Share article