Unable to fetch google cloud bucket image from react.js

    componentDidMount(){
        let default_image = localStorage.getItem("default_image");
        const url = 'https://storage.googleapis.com/smart-staging-bucket/tryon/images/default/2021-03-14/face.jpg'
        const fileName = 'myFile.jpg'
        fetch(url)
        .then(async response => {
            const contentType = response.headers.get('content-type')
            const blob = await response.blob()
            const file = new File([blob], fileName, { contentType })
            this.setState({
            default_image: file
            })
        })
    }

Here i am tying to fetch image from google cloud bucket. But, i am getting below error.Is there any way i can fix it ?

    Access to fetch at 'https://storage.googleapis.com/smart-staging-bucket/tryon/images/default/2021-03-14/face.jpg' from origin
    'http://localhost:3000' 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.

Upvotes: 1

Views: 1598

Answers (1)

countunique
countunique

Reputation: 4296

The Same-Origin Policy is preventing fetch from querying the image. You need to set up Cross-Origin Resource Sharing (CORS) for your Cloud Storage Bucket -- see the docs.

For example,

echo '[{ "origin": ["https://your-site.com"], "method": ["GET"] }]' >cors.json
gsutil cors set cors.json gs://your-bucket

Upvotes: 3

Related Questions