axios
왠만한건 다른 분들이 더 잘 써주셔서..!
axios 를 쓰면 뭐가 더 편해질까에 대해 생각하며 찾아봤습니닷!
- Promise 기반으로 요청 및 응답이 이루어지기 때문에, response 데이터를 다루기 쉽다 (then!)
- 자동으로 JSON 데이터를 처리해준다.
- fetch 는 response timeout 이 없어서 요청 시 계속 기다려야 한다는 문제점이 있다. 하지만 axios 를 사용하면 timeout 옵션 기능을 통해 해당 문제점을 처리할 수 있다.
- baseURL, timeout, header, transformRequest 등등 요청 시 여러 기능들을 지원한다 ⇒ 간단해짐
- 인스턴스를 생성해서 기본 옵션을 계속 재사용할 수 있다 ⇒ 코드 짧아짐
요청 config
axios 를 통한 데이터 요청 시 사용할 수 있는 config 옵션들!
여기에서 가져왔음!
instance 활용
axios 인스턴스를 사용하면 aseURL 과 고정 옵션들을 재사용해서 요청을 보낼 수 있음
baseURL, headers, 등등 여러 옵션들을 한번만 써서 변수에 저장하고, 계속 그 변수에 요청 메소드를 체이닝하면 된다는 뜻!
- 인스턴스 생성
const instance = axios.create({ baseURL: 'https://some-domain.com/api/', timeout: 1000, headers: {'X-Custom-Header': 'foobar'} });
- 인스턴스를 활용한 GET 요청 예시
instance.get('/some-endpoint') .then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); });
- 사용 가능한 인스턴스 메소드
- get, delete, post, put …
- 다 된다!
- 인스턴스를 활용한 POST 요청 예시
const dataToSend = { key1: 'value1', key2: 'value2' }; instance.post('/some-endpoint',dataToSend) .then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); }) axios.post('https://some-domain.com/api/some-endpoint', { timeout: 1000, headers: {'X-Custom-Header': 'foobar'}, data: dataToSend }).then(function (response) { console.log(response.data); }) .catch(function (error) { console.error(error); })