티스토리 뷰
비동기 요청의 대표적인 사례: 네트워크 요청
JSON에서 데이터를 문자열로 다루는 이유는(객체, 배열도)
주고받는 과정에서 데이터가 변하지 않길 바라기 때문
fetch API
: url로 네트워크에 요청할 수 있게 해주는 API
(API: Application Programming Interface. 요청과 응답을 사용하여 두 애플리케이션이 서로 통신하는 방법)
axios 라이브러리
: 브라우저, Node.js를 위한 Promise API를 활용하는 HTTP 비동기 통신 라이브러리
fetch API보다 사용이 간편하고 추가 기능이 있음
| axios | fetch api |
| 3rd-party 라이브러리 | built-in API |
| JSON데이터 자동 변환 | .json() 메서드 사용해야함 |
| response -> data | response.json() -> data |
| axios.get("url" [, config]) | fetch("url", {method: 'GET') |
| axios.post("url" [, data [, config]]) | fetch("url", {method: 'POST', headers: {'Content-type': 'application/json'}, body: 내용} |
axios의 config: 옵션
fetch의 headers: {'Content-Type': 'application/json'} -> JSON 형식으로 데이터를 보낸다고 서버에게 알리는 역할
GET 요청
fetch -출처
// Promise ver
fetch('https://koreanjson.com/users/1', { method: 'GET' })
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error));
// Async / Await ver
// async function request() {
// const response = await fetch('https://koreanjson.com/users/1', {
// method: 'GET',
// });
// const data = await response.json();
// console.log(data);
// }
// request();
const appDiv = document.getElementById('app');
appDiv.innerHTML = `
<h1>Fetch API 😊</h1>
<h3>console 창을 확인해주세요! 👇👇👇</h3>
`;
axios -출처
// axios를 사용하기 위해서는 설치한 axios를 불러와야 합니다.
import axios from 'axios';
// Promise ver
axios
.get('https://koreanjson.com/users/1')
.then((response) => {
const { data } = response;
console.log(data);
})
.catch((error) => console.log(error));
// Async / Await ver
// async function request() {
// const response = await axios.get('https://koreanjson.com/users/1');
// const { data } = response;
// console.log(data);
// }
// request();
const appDiv = document.getElementById('app');
appDiv.innerHTML = `
<h1>Axios ☺️</h1>
<h3>console 창을 확인해주세요! 👇👇👇</h3>
`;
POST 요청
fetch -출처
// Promise ver
fetch('https://koreanjson.com/users', {
method: 'POST',
headers: {
// JSON의 형식으로 데이터를 보내준다고 서버에게 알려주는 역할입니다.
'Content-Type': 'application/json',
},
body: JSON.stringify({ nickName: 'ApeachIcetea', age: 20 }),
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error));
// Async / Await ver
// async function request() {
// const response = await fetch('https://koreanjson.com/users', {
// method: 'POST',
// headers: {
// 'Content-Type': 'application/json',
// },
// body: JSON.stringify({ nickName: 'ApeachIcetea', age: 20 }),
// });
// const data = await response.json();
// console.log(data);
// }
// request();
const appDiv = document.getElementById('app');
appDiv.innerHTML = `
<h1>Fetch API 😊</h1>
<h3>console 창을 확인해주세요! 👇👇👇</h3>
`;
axios -출처
// axios를 사용하기 위해서는 설치한 axios를 불러와야 합니다.
import axios from 'axios';
// Promise ver
axios
.post('https://koreanjson.com/users', { nickName: 'ApeachIcetea', age: '20' })
.then((response) => {
const { data } = response;
console.log(data);
})
.catch((error) => console.log(error));
// Async / Await ver
// async function request() {
// const response = await axios.post('https://koreanjson.com/users', {
// name: 'ApeachIcetea',
// age: '20',
// });
// const { data } = response;
// console.log(data);
// }
// request();
const appDiv = document.getElementById('app');
appDiv.innerHTML = `
<h1>Axios ☺️</h1>
<h3>console 창을 확인해주세요! 👇👇👇</h3>
`;
22.11.24
코스 S2U3
'코드스테이츠(SEB_FE_42)' 카테고리의 다른 글
| [React] SPA(Single Page Application) 만들기 (0) | 2022.11.28 |
|---|---|
| [JS] React Intro (0) | 2022.11.25 |
| [JS, Node.js] Promise, callback (0) | 2022.11.23 |
| [Web APIs] 타이머 관련 API (0) | 2022.11.22 |
| [JS] 비동기(asynchronous), callback, promise, async/ await (0) | 2022.11.22 |
댓글
공지사항
