Front-End/Library

Library] Axios : ์‘์šฉ

์™•๊ฐ€๐Ÿ‘ 2023. 6. 28. 10:35
728x90
๋ฐ˜์‘ํ˜•
2023.06.27 - [Front-End/Library] - Library] Axios

 

์ด์ „ Axios๊ธ€์„ ๊ธฐ๋ฐ˜์œผ๋กœ ๋งˆ์ง€๋ง‰ ์ฝ”๋ฉ˜ํŠธ์— ๋‹ฌ์•˜๋˜ ๋‚ด์šฉ๋“ค์„ ๋‹ค๋ค„๋ณด๋ ค๊ณ  ํ•ฉ๋‹ˆ๋‹ค.

 

 


 

 

๋™์‹œ์š”์ฒญ

axios
.all([axios.get(), axios.get(), req3...])
.then(axios.spread((res1, res2, res3, res4) => {
    // ์š”์ฒญ ์„ฑ๊ณตํ–ˆ์„ ๋•Œ
  })
)

ํ•œ ๋ฒˆ์— ์—ฌ๋Ÿฌ ๊ฐœ์˜ ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ–๊ณ  ์˜ค๊ณ  ์‹ถ์„ ๋•Œ ์‚ฌ์šฉํ•˜๋ฉด ๋  ๋“ฏํ•ฉ๋‹ˆ๋‹ค.

 

 


 

 

Instance

const axiosInstance = () => {
  const instance = axios.create({
    baseURL: 'http://localhost:3000/account',
    withCredentials: true,
    xsrfCookieName: '์ฟ ํ‚ค์ด๋ฆ„',
    xsrfHeaderName: 'ํ—ค๋”์ด๋ฆ„',
    ...
  });
  
  return instance;
};

axiosํ†ต์‹ ์„ ์œ„ํ•œ instanceํ•˜๋‚˜ ๋งŒ๋“ค์–ด ๋ฏธ๋ฆฌ option์„ ์„ค์ •ํ•ด ์ฃผ๊ณ  ์‚ฌ์šฉํ•˜๋ฉด ํŽธ๋ฆฌํ•ฉ๋‹ˆ๋‹ค.

 

 


์ „์—ญ์„ค์ •

axios.defaults.baseURL = 'http://localhost:3000/account';
axios.defaults.withCredentials = true;
axios.defaults.xsrfCookieName = '์ฟ ํ‚ค์ด๋ฆ„';
axios.defaults.xsrfHeaderName = 'ํ—ค๋”์ด๋ฆ„';

instance ๋งŒ๋“ค๊ณ  ๋‚œ ๋’ค, instance.defaults๋กœ ๊ฐ’์„ ์ •ํ•ด์ฃผ๋ฉด default ๊ฐ’์„ ๋ฐ”๊ฟ” ์ค„ ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.

 

 


 

 

์ด๋ฏธ์ง€ ๋‹ค์šด๋กœ๋“œ

axios({
   url: imgurl,
   method: 'GET',
   responseType: 'blob'
})
.then((response) => {
   const url = URL.createObjectURL(new Blob([response.data])); // blob ๋ฐ์ดํ„ฐ๋ฅผ ๊ฐ์ฒด url๋กœ ๋ณ€ํ™˜
   
   // ์ด๋ฏธ์ง€ ์ž๋™ ๋‹ค์šด ๋กœ์ง
   const aTag = document.createElement('a');
   aTag.setAttribute('href', url);
   aTag.setAttribute('download', 'sample.png');
   aTag.click();
   
   URL.revokeObjectURL(url);
 })

 

 


 

 

interceptors

request

axios.interceptors.request.use((config) => {
  // ์š”์ฒญ์ด ์ „๋‹ฌ๋˜๊ธฐ ์ „์— ์ž‘์—… ์ˆ˜ํ–‰
  return config;
}, (error) => {
  // ์š”์ฒญ ์˜ค๋ฅ˜๊ฐ€ ์žˆ๋Š” ์ž‘์—… ์ˆ˜ํ–‰
  return Promise.reject(error);
});

 

response

axios.interceptors.response.use((response) => {
  // ์š”์ฒญ์ด ์ „๋‹ฌ๋˜๊ธฐ ์ „์— ์ž‘์—… ์ˆ˜ํ–‰
  return response;
}, (error) => {
  // ์š”์ฒญ ์˜ค๋ฅ˜๊ฐ€ ์žˆ๋Š” ์ž‘์—… ์ˆ˜ํ–‰
  return Promise.reject(error);
});

 

Interceptor ์ œ๊ฑฐ

const interceptor = axios.interceptors.request.use(() => {});
axios.interceptors.request.eject(interceptor);

 

 


 

 

๊ฐœ๋ฐœํ•  ๋•Œ, axios๊ด€๋ จ๋œ ๋ถ€๋ถ„์„ ๋”ฐ๋กœ ์ •์˜ํ•ด ๋‘๊ณ  ํ•จ์ˆ˜๋กœ ์‚ฌ์šฉํ•˜๋ฉด ์ข€ ๋” ์†Œ์Šค๋ฅผ ๊น”๋”ํ•˜๊ฒŒ ์ž‘์„ฑํ•  ์ˆ˜ ์žˆ์„ ๊ฒƒ ๊ฐ™์Šต๋‹ˆ๋‹ค.
ํ”„๋กœ์ ํŠธ ์ง„ํ–‰ ํ•  ๋•Œ, ๋‹ค๋ฅธ ์‚ฌ๋žŒ์ด ์ž‘์„ฑํ•ด ๋†“์€ ๊ฑฐ ๊ฐ€์ ธ๋‹ค ์“ฐ๊ธฐ๋งŒ ํ–ˆ๋Š”๋ฐ ์ •๋ฆฌํ•  ๊ฒธ ํ•œ๋ฒˆ ๋ณด๋‹ˆ ์ดํ•ดํ•˜๋Š”๋ฐ ๋„์›€์ด ๋์Šต๋‹ˆ๋‹ค.
728x90

'Front-End > Library' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

Library] SWR : ์‘์šฉ_Mutate & Revalidation  (0) 2023.07.03
Library] SWR : ์‘์šฉ  (0) 2023.07.03
Library] SWR  (0) 2023.07.03
Library] Swiper  (0) 2023.06.29
Library] Axios  (0) 2023.06.27