0

I am a beginner in java script. And I have the following script

    function sendImageToBackend(formData) {

        fetch('my-back-end-url', {
            method: 'POST',
            body: formData,
        })
            .then((response) => {
                if (!response.ok) {
                    throw new Error('Error uploading image');
                }
                
                return response.json(); // Parse the response as JSON
            })
            .then((data) => {
                // Handle the received data from the backend
                displayResponseData(data);
            })
            .catch((error) => {
                console.error('Error uploading image:', error);
                // Display an error message to the user
                alert('Error uploading image. Please try again later.');
            });
    }


    function displayResponseData(data) {

        responseContainer.innerHTML = '';

        const heading = document.createElement('h2');
        heading.textContent = 'Response Data:';
        responseContainer.appendChild(heading);

        const dataParagraph = document.createElement('p');
        dataParagraph.textContent = JSON.stringify(data);
        responseContainer.appendChild(dataParagraph);
    }
});

So my Back-End accepts an image and it takes some time to process it. And the Back-End will return an image to the front-end. I did test my back-end (an FastAPI on Cloud Run) and it works, but I have problem with java script. Do you know how to fix it? So I want to display the image from the backend.

  • 1
    By "image" are you talking about the _URL_ of the image that's in the JSON that's being returned? – Andy Jun 14 '23 at 17:07
  • Can you add the json or the image field in the json? Is the image encoded as string or send as url? – kennarddh Jun 14 '23 at 17:09
  • The image is encoded as string. So currently I have the follwoing error: "Access to fetch at 'back-end' from origin 'http://127.0.0.1:8080' 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." – Thanh Long Phan Jun 14 '23 at 17:12
  • If the string is in `base64` you can just set it as `src` in the image element. For the cors error you can see this https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe. – kennarddh Jun 14 '23 at 17:15
  • 1
    Looks like there's [some info about configuring cors on CloudRun/API gateway](https://www.googlecloudcommunity.com/gc/Serverless/Cloud-run-cors-policy/m-p/512265/highlight/true#M1058) which maybe useful. – Andy Jun 14 '23 at 17:17

1 Answers1

0

So I fix the problem. I used fastapi and we change to this

app = FastAPI()
...    
app.add_middleware(
        CORSMiddleware,
        allow_origins=["*"], 
        allow_methods=("GET", "POST"),
        allow_headers=["*"]
    )

and test it, and it works.

  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 16 '23 at 15:42