【问题标题】:Unable to fetch google cloud bucket image from react.js无法从 react.js 获取谷歌云存储桶图像
【发布时间】:2021-03-15 11:38:47
【问题描述】:
    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.

【问题讨论】:

标签: reactjs google-cloud-platform google-cloud-storage


【解决方案1】:

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

例如,

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-15
    • 1970-01-01
    • 2018-08-26
    • 2016-10-05
    • 2016-01-31
    相关资源
    最近更新 更多