skip to Main Content

I’m trying to generate a variation of my image using openai’s image variation api endpoint. It throws CORS error

Suggest me a solution using vanilla js.

This is the code snippet, that i have tried

requestImageVariation(image) { //image is base64 url of png image

        let data = {
            image: image,
            n: 4
        }

        const options = {
            method: "POST",
            headers: {
            "Content-Type": "application/json",
            Authorization: `Bearer ${apiKey}`,
        },
            body: JSON.stringify(data),
        };

        fetch("https://api.openai.com/v1/images/variations", options)
            .then(res => res.json())
            .then(res =>console.log(res))
            .catch(err=>console.log(err))

    }

As im getting the image from canvas element, base64 is easier. Suggest me if i should change this img type

If you have any other alternate way of sending the image for the API, please let me know

2

Answers


  1. you can try running you project on local server :

    // shell commands
    npm install --global http-server
    

    then navigate to your project directory and run :

     http-server
    
    Login or Signup to reply.
  2. In situations like these, you can consider using a proxy service to bypass the CORS issue while still keeping everything client-side. There are third-party services available that act as a proxy to make requests on behalf of your frontend application and handle CORS headers. One such service is CORS Anywhere (https://cors-anywhere.herokuapp.com/).

    function requestImageVariation(image) {
        const data = {
            image: image,
            n: 4,
        };
    
        const options = {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-Requested-With': 'XMLHttpRequest', // Required for CORS Anywhere
            },
            body: JSON.stringify(data),
        };
    
        const proxyUrl = 'https://cors-anywhere.herokuapp.com/';
        const apiUrl = 'https://api.openai.com/v1/images/variations';
    
        fetch(proxyUrl + apiUrl, options)
            .then((res) => res.json())
            .then((res) => console.log(res))
            .catch((err) => console.log(err));
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search