✘✘✘ 개발일기
How to load images that needs to be authorized with Axios
PrettyLog
2022. 10. 10. 19:02
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;
}