Axios

๊น€๋‚จ๊ฒฝยท2022๋…„ 12์›” 19์ผ

server

๋ชฉ๋ก ๋ณด๊ธฐ
7/7

์˜๋ฏธ

๐Ÿ’ก Node.js๋ฅผ ์œ„ํ•œ Promise API๋ฅผ ํ™œ์šฉํ•˜๋Š” HTTP ๋น„๋™๊ธฐ ํ†ต์‹  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
๐Ÿ’ก ์„ค์น˜๊ฐ€ ๋ณ„๋„ ํ•„์š”
๐Ÿ’ก ์ž๋™์œผ๋กœ JSON๋ฐ์ดํ„ฐ๋กœ ๋ณ€ํ™˜๋จ

์„ค์น˜

npm install axios

GET

๐Ÿ“— fetch

//Promise
fetch(URL, {method : 'GET'})
  .then((response) => response.json())
  .then((json) => return json)
  .catch((error) => console.log(error));

//Async & await
async function x() {
  const response = await fetch(URL, {method : 'GET'});
  const data = await response.json();
  return data;
}

x();

๐Ÿ“— axios

//Promise
import axios from 'axios';

axios
  .get(URL)
  .then((response) => {
    const { data } = response;
    return data;
  })
  .catch((error) => console.log(error));

//Async & await
async function x(){
  const response = await axios.get(URL);
  const { data } = response;
  return data;
}

x();

POST

๐Ÿ“— fetch

//Promise
fetch(URL, {
  method : 'POST',
  headers : {
    'Content-Type' : 'application/json',
  },
  body : JSON.stringify({ name : 'a', number : 1 }),
})
  .then((response) => response.json())
  .then((json) => return json)
  .catch((error) => console.log(error));

//Async & await
async function x() {
  const response = await fetch(URL, {
    method : 'POST',
    headers : {
      'Content-Type' : 'application/json',
    },
    body : JSON.stringify({ name : 'a', number : 1 }),
  });
  const data = await response.json();
  return data;
}

x();

๐Ÿ“— axios

//Promise
import axios from 'axios';

axios
  .post(URL, {
    name : 'a', number : 1
  })
  .then((response) => {
    const { data } = response;
    return data;
  })
  .catch((error) => console.log(error));

//Async & await
async function x() {
  const response = await axios.post(URL, {
      name : 'a', number : 1
  });
  const data = await response.json();
  return data;
}

x();
profile
๊ธฐ๋ณธ์— ์ถฉ์‹คํ•˜๋ฉฐ ์•ž์œผ๋กœ ๋ฐœ์ „ํ•˜๋Š”

0๊ฐœ์˜ ๋Œ“๊ธ€