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();
axios
// axios를 사용하기 위해서는 설치한 axios를 불러와야 합니다.
import axios from 'axios';
// Promise ver
axios
.get('https://koreanjson.com/users/1')
.then((response) => {
console.log(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();
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();
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();
'프론트엔드 개발 > JavaScript' 카테고리의 다른 글
JavaScript - call, apply, bind (0) | 2023.01.31 |
---|---|
flat() 쓰지 않고 중첩 배열 평탄화 (0) | 2023.01.28 |
정규표현식 (0) | 2023.01.25 |
javascript 24시간 형식 표시(HH:MM) (0) | 2023.01.10 |
정규표현식 굉장히 잔뜩 기초만 쉽게 (0) | 2023.01.06 |