๐Ÿ“ฅ Axios

์ง€์€ยท2022๋…„ 11์›” 10์ผ
0

Node.js Library

๋ชฉ๋ก ๋ณด๊ธฐ
12/14
post-thumbnail

Axios

: Node.js์™€ ๋ธŒ๋ผ์šฐ์ €๋ฅผ ์œ„ํ•œ, Promise ๊ธฐ๋ฐ˜ HTTP ๋น„๋™๊ธฐ ํ†ต์‹  ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ

Axios ๊ณต์‹ ๋ฌธ์„œ

Fetch API vs Axios

Axios๋Š” Fetch API์™€ ๋น„์Šทํ•œ ์—ญํ• ์„ ํ•˜์ง€๋งŒ, Fetch API๋ณด๋‹ค ์‚ฌ์šฉ์ด ๋” ๊ฐ„ํŽธํ•˜๋ฉด์„œ ์ถ”๊ฐ€์ ์ธ ๊ธฐ๋Šฅ๋“ค์ด ํฌํ•จ๋˜์–ด ์žˆ๋‹ค.

Fetch APIAxios
๋นŒํŠธ์ธ API๋ผ ๋ณ„๋„์˜ ์„ค์น˜๊ฐ€ ํ•„์š” ์—†๋‹ค.์จ๋“œ ํŒŒํ‹ฐ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋กœ ์„ค์น˜๊ฐ€ ํ•„์š”ํ•˜๋‹ค.
.json() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•ด์•ผ ํ•œ๋‹ค.์ž๋™์œผ๋กœ JSON ๋ฐ์ดํ„ฐ ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜ํ•ด์ค€๋‹ค.

Axios ์‚ฌ์šฉ๋ฒ•

Axios ์„ค์น˜ํ•˜๊ธฐ

  1. npm install ๋ช…๋ น์–ด๋กœ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ๋ฅผ ๋‹ค์šด๋ฐ›๋Š”๋‹ค.
npm install axios
  1. Axios๋ฅผ ์‚ฌ์šฉํ•  ํŒŒ์ผ์—์„œ importํ•ด์ค€๋‹ค.
import axios from 'axios';

GET ์š”์ฒญ

axios.get("url"[, config])
  • ์ฒซ ๋ฒˆ์งธ ์ธ์ž์—๋Š” url ์ฃผ์†Œ๊ฐ€ ๋“ค์–ด๊ฐ„๋‹ค. (ํ•„์ˆ˜)
  • ๋‘ ๋ฒˆ์งธ ์ธ์ž์—๋Š” ์š”์ฒญ ์‹œ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋Š” ์˜ต์…˜๋“ค์„ ์„ค์ •ํ•  ์ˆ˜ ์žˆ๋‹ค. (ํ•„์ˆ˜ X)

์˜ˆ์‹œ) Promise ์‚ฌ์šฉ

axios
  .get('https://koreanjson.com/users/1')
  .then((response) => {        // axios๋Š” ์ž๋™์œผ๋กœ JSON ๋ฐ์ดํ„ฐ ํ˜•์‹์œผ๋กœ ๋ณ€ํ™˜ํ•˜๊ธฐ ๋•Œ๋ฌธ์—
    const { data } = response; // .json() ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜์ง€ ์•Š์•„๋„ ๋œ๋‹ค.
    console.log(data);
  })
  .catch((error) => console.log(error));

์˜ˆ์‹œ) Async / Await ์‚ฌ์šฉ

async function requestData() {
  const response = await axios.get('https://koreanjson.com/users/1');
  const { data } = response;
  console.log(data);
}

requestData();

POST ์š”์ฒญ

axios.post("url"[, data [, config]])

DELETE ์š”์ฒญ

axios.delete("url"[, config])
  • ๊ธฐ๋ณธ์ ์œผ๋กœ Axios์˜ delete ๋ฉ”์†Œ๋“œ๋Š” ์š”์ฒญ ๋ฐ”๋””์— ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์„ ์ˆ˜ ์—†๋‹ค.
  • ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์–ด ์š”์ฒญ์„ ๋ณด๋‚ด๊ณ  ์‹ถ๋‹ค๋ฉด, ๋‘ ๋ฒˆ์งธ ์ธ์ž์— data: {} attribute๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  ์•ˆ์— ๋ฐ์ดํ„ฐ๋ฅผ ๋„ฃ์–ด์ฃผ๋ฉด ๋œ๋‹ค.
axios.delete("url", { data: {...} })

์˜ˆ์‹œ)

axios
  .delete("url", { data: { accessToken } })
  .then((res) => {
    setIsLogin(false);
    setAccessToken('');
    setGithubUser(null);
    setServerResource(null);
}); 
profile
๋ธ”๋กœ๊ทธ ์ด์ „ -> https://janechun.tistory.com

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