Error 400 with Direct Creator Upload in React

Hello!

I’m trying to use Cloudflare Images with React, specifically the Direct Creator Upload.

Here is my code:

export function ImageUpload({ label, onChange, value, name }: Props) {
  let handleFileChange = async (e: any) => {
    const file = e.target.files[0];
    const res = await fetch("/api/r2");
    const { id, uploadURL } = await res.json();
    if (!uploadURL) {
      throw new Error("No upload url");
    }
    console.log("1️⃣", id, uploadURL, file, file.name);

    const formData = new FormData();
    formData.append("myFile", file, file.name);

    const res2 = await fetch(uploadURL, {
      method: "POST",
      body: formData,
    });

    // 🚨 Can't upload 👆
    // Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://upload.imagedelivery.net/XXX. (Reason: CORS request did not succeed).

    console.log("2️⃣", res2.status);
    if (res2.status !== 200) {
      throw new Error("Upload failed");
    }

    const res3 = await fetch(`/api/r2?id=${id}`);
    const json3 = await res3.json();
    console.log("3️⃣", json3);
  };

  return (
    <div>
      <input type="file" onChange={handleFileChange} />
      <button type="button">Upload file</button>
      {value && <img src={value} alt="Upload" />}
      <hr />
    </div>
  );
}

Acquiring the upload URL works fine, but when I try to upload the image I just get a 400 error without any response. How can I debug this? Any suggestions on what I should change in my code?

I found this thread: CORS error when using Direct Creator Upload - #14 by yevgen where it says this has been solved, but I’m still seeing this error

Best regards
Max

Hi, can you dump preflight request/response headers?

Since the error you posted is about errored CORS request:

Reason: CORS request did not succeed

Would be also good to know what exactly failed.

This topic was automatically closed after 15 days. New replies are no longer allowed.