문제해결/프로젝트&협업
[프로젝트 코드 다시 뜯어보기] axios 인스턴스 까보기(class와 promise 문법을 중심으로)
whale in milktea
2023. 7. 2. 23:24
1. Axios의 클래스와 인스턴스
- axios는 javascript의 클래스를 사용하여 구현되어있다.
- axios.get / post 등 모든 메서드는 axios.create()를 통해 생성된 "인스턴스"이다.
2. Axios create의 기본구조
// 기본문법
axios.create([config])
const myAxios = axios.create({
baseURL: 'https://some-domain.com/api/',
timeout: 1000,
headers: {'X-Custom-Header': 'foobar'}
});
// 이제 내가 미리 설정한 myAxios라는 커스텀 인스턴스에 내가 원하는 메서드를 붙여서 HTTP 통신 동작을 수행할 수 있다.
const myAxios.post (data)
3. Promise의 기반한 Axios
- axios는 Promise를 기반으로 한 HTTP 클라이언트 라이브러리이다.
- axios가 담당하는건, promise 함수를 통한 비동기처리 작업과 서버 통신을 위한 HTTP 메서드의 제공이다.
- 나머지는 Promise와 똑같다.
4. 코드 뜯어보기 (formData 이미지 업로드 함수)
// MemberProfileUpdateImageDto라는 interface에 정의된 타입대로 image 변수의 객체가 인자로 전달된다.
// if) image 변수 내부의 image 객체에 모종의 이유로 접근할 수 없거나, undefiend가 return되면 Error 객체를 리턴한다.
// formData 객체를 생선한 이후 "image"라는 키값에 "image.image"라는 데이터를 저장한다.
// 별도로 정의된 tokenRequestApi라는 axios 인스턴스에 patch 메서드를 사용하여 url / data / header를 적용하여 서버에 요청을 전달한다.
export const updateMemberProfileImage = async (
image: MemberProfileUpdateImageDto
) => {
if (!image.image) throw new Error("이미지를 확인해주세요.");
const formData = new FormData();
formData.append("image", image.image);
await tokenRequestApi.patch("/members/image", formData, {
headers: {
"Content-Type": "multipart/form-data",
},
});
};