微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

无法从 react.js 获取谷歌云存储桶图像

如何解决无法从 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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。