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;
}
'✘✘✘ 개발일기' 카테고리의 다른 글
[Vanilla][Javascript] 기본들 (0) | 2022.11.13 |
---|---|
[Webpack] Webpack dev server config (0) | 2022.10.10 |
Why buffer makes IOs fast (0) | 2022.10.10 |
How to change themes between light and dark, @media (0) | 2022.10.10 |
[메모] lazy loading with intersectionObserver, 로더, localstorage (0) | 2022.10.10 |
댓글