Cloudflare - R2 Bucket CORS 에러 해결하기

2024. 12. 29. 23:51· Trouble Shooting
목차
  1. 개요
  2. 조사
  3. 해결
  4. 교훈

Cloudflare - R2 Bucket CORS 에러 해결하기

 

작성일자 : 2024_년 12월 29일


 

(이미지)

 

개요

 

아래와 같은 JS 코드에서 Cloudflare R2 Bucket에 있는 이미지를 불러오려고 할 때, CORS 에러가 발생하였다.

const createImage = (url: string): Promise<HTMLImageElement> => {
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.addEventListener("load", () => resolve(image));
    image.addEventListener("error", error => reject(error));
    image.setAttribute("crossOrigin", "anonymous");
    image.src = url;
  });
};

 


 

이미 해당 R2 Bucket의 CORS policy를 설정해주었음에도 불구하고, 여전히 CORS 에러가 발생하였다.

 

설정하였던 CORS policy

[
  {
    "AllowedOrigins": [
      "http://localhost:3000"
    ],
    "AllowedMethods": [
      "GET"
    ],
  }
]

 


 

 

조사

 

해당 문제의 특별했던 점은, 크롬 개발자 도구에서 Network 탭을 확인해보면 memory cache 또는 disk cache에서 이미지를 불러오려고 시도하고 있었다는 것이었다.

 

이를 보고 아래와 같이 Disable cache를 체크하고 다시 시도해보았더니, CORS 에러가 발생하지 않았다.

 

Disable cache 체크

 


 

위의 증거를 바탕으로 추가 검색을 진행하였으며, 불과 얼마 전에 올라온 아래와 같은 Stackoverflow 글을 찾을 수 있었다.

  • Stackoverflow - Only getting CORs issues when caching is enabled
 

Only getting CORs issues when caching is enabled

I'm getting a very odd combination of CORs issues when trying to do a fetch request for an object hosted in R2 (Cloudflare S3 equivalent): If I disable cache in devtools: Then, I have no CORs iss...

stackoverflow.com

 

  • https://developers.cloudflare.com/r2/buckets/cors/
 

Configure CORS · Cloudflare R2 docs

Cross-Origin Resource Sharing (CORS) ↗ is a standardized method that prevents domain X from accessing the resources of domain Y. It does so by using special headers in HTTP responses from domain Y, that allow your browser to verify that domain Y permits

developers.cloudflare.com

 


 

 

해결

 

위의 글을 바탕으로 JS 코드는 아래와 같이 fetch + "Cache-Control": "no-cache"를 사용하여 이미지를 불러오도록 수정하였다.

const createImage = async (url: string): Promise<HTMLImageElement> => {
  const response = await fetch(url, {
    cache: "no-store",
    headers: {
      "Cache-Control": "no-cache",
    },
  });
  const blob = await response.blob();
  const objectUrl = URL.createObjectURL(blob);
  return new Promise((resolve, reject) => {
    const image = new Image();
    image.onload = () => {
      URL.revokeObjectURL(objectUrl);
      resolve(image);
    };
    image.onerror = reject;
    image.src = objectUrl;
  });
};

 


 

또한, CORS policy는 아래와 같이 설정하였다.

[
  {
    "AllowedOrigins": [
      "http://localhost:3000"
    ],
    "AllowedMethods": [
      "GET"
    ],
    "AllowedHeaders": [
      "Cache-Control"
    ]
  }
]

 


교훈

잊지 말자! 디버깅 툴은 언제나 개발자에게 답을 말하고 있으며, 고객은 로그를 통해 우리에게 말을 걸고 있다.

저작자표시 (새창열림)
  1. 개요
  2. 조사
  3. 해결
  4. 교훈
'Trouble Shooting' 카테고리의 다른 글
  • GithubActions에서 CloudFlare WAF ByPass하기
  • 스프링 - Google OAuth2 로그인 redirect_uri_mismatch
  • NextJS - ReferenceError: File is not defined 해결하기
  • GithubActions - ERROR: failed to solve: process "/dev/.buildkit_qemu_emulator... 해결하기
gerrymandering
gerrymandering
gerrymandering
gerrymandering
gerrymandering
전체
오늘
어제
  • 분류 전체보기 (82)
    • SOLID 원칙 (6)
    • 번역 (4)
    • Nginx (1)
    • Tailwind CSS (1)
    • AWS (7)
      • DMS를 사용한 RDS to OpenSearch .. (3)
      • ECS를 이용한 Blue-Green 무중단 배포 .. (7)
    • NextJS (6)
    • 기타 (12)
    • Prompt Engineering (6)
    • 읽어볼만한 글 (3)
      • 기술 (0)
      • 쓸만한 툴 (0)
      • 아이템 (0)
      • 웹 디자인 (0)
      • 기타 (3)
    • Cloud Architecture (4)
    • Trouble Shooting (9)
    • Spring (11)

블로그 메뉴

  • 홈
  • 태그
  • 방명록

공지사항

인기 글

최근 댓글

최근 글

글쓰기 / 관리자
hELLO · Designed By 정상우.v4.2.1
gerrymandering
Cloudflare - R2 Bucket CORS 에러 해결하기
상단으로

티스토리툴바

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.