[TIL #61] 마이페이지 이미지 변경

차슈·2024년 7월 31일
0

TIL

목록 보기
61/70
post-thumbnail

이쯤되면 그냥 진짜 마이페이지 이미지 변경이란 변경은 다해본거 같지만, 매번 다른 방식으로 변경해서 매번 나는 에러들;;


문제

프로필 변경이 되지 않는 문제가 발생했다. 이미지 url은 들어오는데 이미지가 변하지 않는 문제가 있었다.

  async imageUpload(editimage: File): Promise<string> {
    const formData = new FormData();
    formData.append('editimage', editimage);
   
    try {
      const response = await this.request<{url: string}>(
        '/api/auth/user-image', 
        'POST', 
        formData, 
      );
      return response.url;
    } catch (error) {
      console.error('Image upload failed:', error);
      throw error;
    }
  }


}

해결

처음에는 class method를 할때, 비동기로 안하고 바로 반환 fetch 하는 곳에서 method가 json 형식인데 formdata는 강제로 json이 되어서 type error가 난게 첫번째 이유고,
두번째 이유는, fetch하는 데이터 response를 await json 반환처리 안해서 였다.

  async imageUpload(editimage: File): Promise<string> {
    const formData = new FormData();
    formData.append('editimage', editimage);
    
    try {
      const response = await fetch('/api/auth/user-image', {
        method: 'POST',
        body:formData

      })

      const data = await response.json();
  
    
      return data.imageUrl;
    } catch (error) {
      console.error('Image upload failed:', error);
      throw error;
    }

axios...쓸래......

0개의 댓글