无法从 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
            })
        })
    }

在这里,我想从谷歌云存储桶中获取图像。 但是,我遇到了以下错误。有什么办法可以解决吗?

    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.

解决方法

同源政策阻止 fetch 查询图像。您需要为您的云存储存储桶设置跨域资源共享 (CORS) - 请参阅 docs

例如

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