이번글은 강의보다는
에러로그이다.
상황은 이러하다.
웹사이트가 있다.
이 웹사이트는 s3에서 정적 웹호스팅을 하였고 이를 cloudfront로 감싼다음 가비아에서 산 도메인으로 https 적용을 해둔 상태.
이 웹사이트에서는 이미지를 보여주게 되어있는데 이 이미지들은
다른 s3에서 불러오게 되어있으며
이 경로는 s3로 다이렉트로 가는 것이 아닌
마찬가지로 cloudfront로 cdn 연결을 해둔 상태이다..
일단 문제였던 나의 react.js에서 pdf를 다운받는 코드는 다음과 같다 (물론 코드에는 아무 문제가 없다 현재는 해결된 상태이므로...)
import React from 'react';
import { Button } from '@mui/material';
import html2pdf from 'html2pdf.js'; // html2pdf.js 임포트
import { use } from 'react';
const PDFDownloadButton = () => {
const convertImageToBase64 = async (imageUrl) => {
try {
const response = await fetch(`${imageUrl}?not-from-cache-please`, {
method: 'GET',
mode: 'cors',
});
const blob = await response.blob();
return new Promise((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result);
reader.readAsDataURL(blob);
});
} catch (error) {
console.error('Image conversion failed:', error);
return null;
}
};
const handleDownloadPDF = async () => {
const element = document.getElementById('table-to-download');
// Find all images in the element
const images = element.getElementsByTagName('img');
// Convert all images to base64
for (let img of images) {
const originalSrc = img.src;
const base64Src = await convertImageToBase64(originalSrc);
if (base64Src) {
img.src = base64Src;
}
}
const opt = {
margin: 1,
filename: 'table.pdf',
image: { type: 'jpeg', quality: 0.98 },
html2canvas: {
scale: 2,
useCORS: true,
logging: true
},
jsPDF: {
unit: 'mm',
format: 'a4',
orientation: 'portrait'
}
};
// Generate and save PDF
html2pdf().from(element).set(opt).save();
};
return (
<Button variant="contained" onClick={handleDownloadPDF}>
Download PDF
</Button>
);
};
export default PDFDownloadButton;
pdf의 경우 다시 다운로드 받은 후 pdf 생성시 넣어주어야 하기때문에 다운로드가 필요하다.
다만 여기서 생기는 오류는 나는 다음과 같았다.
Access to fetch at 'https://클라우드프론트주소/images/cchanel.webp?not-from-cache-please' from origin 'https://abcdefg.kr' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. cloud
CORS에러...? 라고 하기에는 몇개는 이미지가 다운로드가 된상태로 pdf에 나오고 몇개는 안나온다는 사실을 캐치..
누가 봐도 캐시문제 그리고 나의 컴퓨터가 아닌 cdn의 즉
CloudFront의 캐시문제라고 보인다는 것이었다. (이 정도면 나도 서린이보다는 서버청소년 정도로 랩업한듯하다)
나의 이미지가 들어있는 s3 버킷은 cors를 완벽하게 모두 허용으로 후후 해놨었다..
클라우드프론트 - 배포 - 동작편집 으로 가자 (나의 경우는 * 기본 하나밖에 없었으므로 이것을 편집)
캐시 정책에서
처음에 cachingoptimized를 disabled로 변경. 이러면 바로바로 적용이 된다고 한다.
그리고 문제는 클라우드프론트가 응답을 캐시하면서 Access-Control-Allow-Origin 헤더를 제거했을 수 있다는 지피티선생의 말에 따라서 명시적으로 응답헤더를 반환해야겠다고 생각하엿다.
응답 헤더 정책 - 선택사항에 Create 헤더로 만든다.
위와 같이 만들고 돌아와서 적용시킨후 변경 사항 저장을 한다.
그 후 브라우저 캐시를 모두 날리고 다시 시도한 결과 아주 깔끔하게.
pdf의 모든 이미지들이 잘 다운받아지고 나타나는 것을 확인..
퓨퓨퓨 이것은
나를 위한 기록..
위의 pdf 작성의 경우 조만간 글을 쓸 요량이다...
'프로그래밍 > Backend' 카테고리의 다른 글
[FastAPI] AWS LightSail에서 DockerCompose ssl (https) 적용하기 (0) | 2025.02.05 |
---|---|
[FastAPI] docker compose로 fastapi & mysql aws LightSail에 배포하기 (0) | 2025.01.23 |
[FastAPI] MySQL 한글이 깨져 보일 때 (feat: 파워쉘, cmd등) (0) | 2025.01.16 |
[FastAPI] pydantic v2 - orm_mode를 마이그레이션.. (0) | 2025.01.12 |