Axios로 이미지 요청해 렌더링

임택·2022년 6월 22일
0

문제해결

목록 보기
2/3

img src 이미지 요청 401 UnAuthorized

문제: img tag 요청이 401 status를 response unauthorized
해결: fetch or axios를 사용해 http request에 Authorization 헤더를 주입해 주어야 한다

Axios 사용해 image http request 하기

why? Authorization: Bearer JWT token 이 필요하다

요청하기

async fetchWithAuthentication(url, authToken, responseType) {
  const res = await axios.get(url, {
    responseType,
  });
  return res;
},

base64 or blob를 사용해 이미지 렌더링

async displayProtectedImageBlob(dom, imageUrl) {
    const response = await this.fetchWithAuthentication(
        imageUrl,
        undefined,
        'blob'
    );
    const objectUrl = URL.createObjectURL(response.data);
	const domToMount = document.createElement('img');
  	domToMount.src = objectUrl;
    domToMount.onload = () => URL.revokeObjectUrl(objectUrl);
	return domToMount;
}
async displayProtectedImageBase64(dom, imageUrl) {
    const response = await this.fetchWithAuthentication(
      imageUrl,
      undefined,
      'arraybuffer'
    );

    const contentType = response.headers['content-type'];

	const domToMount = document.createElement('img');
    const binaryData = Buffer.from(response.data, 'binary');
    const base64 = binaryData.toString('base64');
    const dataUrl = `data:${contentType};base64,${base64}`;        
	return domToMount;
}
profile
캬-!

0개의 댓글