반응형
React에서 axios를 모듈화 시키는 방법입니다.
axios를 모듈화 시키는 이유
아래는 axios를 일반적으로 만드는 여러가지 방법중 하나입니다.
App.js
import axios from 'axios';
import { useEffect } from 'react';
const App = () => {
const serverUrl = 'http://localhost:4000/api/find';
useEffect(() => {
axios.get(serverUrl)
.then(res => {
})
.catch(err => console.log(err));
}, [])
}
export default App;
위와 같이 사용할 경우 serverUrl를 계속해서 가지고 다녀야 하는 상황이 생깁니다. 이럴때 모듈화를해서 사용하면 자동으로 값을 넣어줄 수 있습니다.
axios를 모듈화 시키기
api.js
import axios from "axios";
const api = axios.create({
baseURL: "http://localhost:4000/api",
headers: {}
});
export { api };
App.js
import axios from 'axios';
import { useEffect } from 'react';
const App = () => {
useEffect(() => {
axios.get('/find')
.then(res => {
})
.catch(err => console.log(err));
}, [])
}
export default App;
모듈화를 시켰을때 장점은 serverUrl을 따로 써줄 필요성이 사라졌고, headers( ex: 사용자 토큰 )를 태워서 보내줄 수 있습니다.
반응형
'React > React' 카테고리의 다른 글
[ React ] 삼항연산자를 이용해서 style, className 추가하기 (0) | 2022.11.02 |
---|---|
[ React ] map() 반복문을 통한 컴포넌트 생성하기 (0) | 2022.10.27 |
[ React ] className 여러개 적용 시키기 (0) | 2022.10.27 |
[ React ] react-router-dom (0) | 2022.10.20 |
[ React ] gh-pages를 이용해서 웹 페이지 호스팅하기 (0) | 2022.10.14 |