1

This is my API request code for Replicate AI API and it is showing CORS error, and I tried adding the line below to headers but it still didn't work...

'Access-Control-Allow-Origin':'*',
'Access-Control-Allow-Methods':'POST,PATCH,OPTIONS'

This is the error:

Access to fetch at 'https://api.replicate.com/v1/predictions' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

This is my API request code

const generateRoom = async (item) => {
    try {
      await new Promise((resolve) => setTimeout(resolve, 200));
      setResload(true);
      const idan = generateRandomId(8);
      const blobo = new Blob([selectedImage], { type: "image/jpeg" });

      const startResponse = await fetch(
        "https://api.replicate.com/v1/predictions",
        {
          method: "POST",
          headers: {
            "Content-Type": "application/json",
            Authorization: "Token token_code",
          },
          body: JSON.stringify({
            version:
              "854e8727697a057c525cdb45ab037f64ecca770a1769cc52287c2e56472a247b",
            input: {
              image: URL.createObjectURL(blobo),
              prompt:
                room === "Gaming Room"
                  ? "a room for gaming with gaming computers, gaming consoles, and gaming chairs"
                  : `a ${item.toLowerCase()} ${room.toLowerCase()}`,
              a_prompt:
                "best quality, extremely detailed, photo from Pinterest, interior, cinematic photo, ultra-detailed, ultra-realistic, award-winning",
              n_prompt:
                "longbody, lowres, bad anatomy, bad hands, missing fingers, extra digit, fewer digits, cropped, worst quality, low quality",
            },
          }),
        }
      );

      if (startResponse.ok) {
        const jsonStartResponse = await startResponse.json();
        const endpointUrl = jsonStartResponse.urls.get;

        let restoredImage = null;
        while (!restoredImage) {
          const finalResponse = await fetch(endpointUrl, {
            method: "GET",
            headers: {
              "Content-Type": "application/json",
              Authorization: "Token token_code",
            },
          });
          const jsonFinalResponse = await finalResponse.json();

          if (jsonFinalResponse.status === "succeeded") {
            restoredImage = jsonFinalResponse.output;
          } else if (jsonFinalResponse.status === "failed") {
            throw new Error("Image restoration failed");
          } else {
            await new Promise((resolve) => setTimeout(resolve, 1000));
          }
        }

        setImgs((prevImgs) => [
          ...prevImgs,
          <AspectRatio ratio={1}>
            <Button
              backgroundImage={`url(${restoredImage})`}
              backgroundPosition={"center"}
              backgroundSize={"cover"}
              colorScheme="transparent"
              _hover={{
                opacity: 0.9,
              }}
            ></Button>
          </AspectRatio>,
        ]);
      } else {
        const error = await startResponse.json();
        console.log("Error: ");
        throw new Error(error.message);
      }
    } catch (error) {
      console.log(error);
    } finally {
      setTimeout(() => {
        setResload(false);
      }, 1300);
    }
  };
VLAZ
  • 26,331
  • 9
  • 49
  • 67

0 Answers0