프론트엔드 개발/JavaScript

fetch axios

하이고니 2023. 1. 23. 17:32

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();