无法修复谷歌云存储上的CORS策略



我试图从React应用程序上传文件到谷歌云存储的桶。我已经启用了CORS设置的桶,但似乎我仍然无法从web应用程序访问。我得到以下错误:

Access to fetch at 'https://storage.googleapis.com/my_unique_bucket/ABCdio%20Vi?GoogleAccessId=storage-ucardia%40ucardia-297520.iam.gserviceaccount.com&Expires=1612456695&Signature=oxb2LVj22hc4%2FsnskKIwaq%2BK9qq88yAmnAGN1pbRJ%2BPJ2d68%2BHRRBYS24xPNwBLSkVktsjSWTBBoWv5tTkCuUAzG3Q2Q51gLdoaLUmFyGt8a4hgKJ94DeTaAJL0Hf0rwz0sNx6SkSdqrrQF%2BGlRH4HYI10JBQHuw3%2BQMPIW%2FRXTlfcvjdCkdRT9vX6twjBrC4bdIijvB31SvxbipQHWuhh6QjlKtybp3OW8kV2tY00KNWv0pE98%2FCRDBikzVkyZwM8WOYEXWUuxY9lem9LYjkBo%2BafQECApvkTQVjg%2FWJo%2BUCTVpnO5wKL58BN2QCqkmG%2FIPAwg0ptQJVMcxFhfCZw%3D%3D' from origin 'https://dashboard-fe.uc.r.appspot.com' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 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.

JSON文件中的CORS设置如下:

[]

然而,我也尝试过在JSON中指定web URL和PUT方法的设置,但没有工作。

更新1:

node . js API:

const storage = new Storage({
keyFilename: path.join(__dirname, '../../../projectId.json'),
projectId: 'projectId',
});
storage.getBuckets().then((x) => {
console.log(x);
});
const generateSignedUrl = async (req, res) => {
const { filename, filetype } = req.query;
// These options will allow temporary read access to the file
const options = {
version: 'v2', // defaults to 'v2' if missing.
action: 'write',
expires: Date.now() + 1000 * 60 * 60, // one hour
contentType: 'application/x-www-form-urlencoded',
};
try {
// Get a v2 signed URL for the file
const [url] = await storage.bucket('my_unique_bucket').file(filename).getSignedUrl(options);
res.status(ok).json({ data: url, message: GENERATE_SIGNED_URL_SUCCESS, status: true });
} catch (error) {
res.status(internalServerError).json({ error, status: false, message: GENERATE_SIGNED_URL_FAILED });
}
};

Reactjs客户:

export const putFile = async ({ url, file }) => {
const method = 'PUT';
return await fetch(`${url}`, {
body: file,
method,
headers: {
// Accept: file.type,
'Content-Type': file.type,
'Access-Control-Allow-Origin': '*',
},
});
};

更新2:这个链接说,这是一个问题与URL的形成,但我得到的URL作为预设的URL从谷歌云存储NPM包。顺便说一句,我已经按照这个链接建立了机制,但似乎我错过了一些非常明显的东西。

很抱歉回复晚了。我注意到你的代码有些奇怪。在JSON文件

中有这个配置
[]

然而,在你的react客户端你有这个

headers: {
// Accept: file.type,
'Content-Type': file.type,
'Access-Control-Allow-Origin': '*',
}

如果JSON文件中有[],则从桶中删除CORS。尽管如此,您仍然在发送值。您需要将此添加到JSON文件中以设置bucket中的CORS。

({"origin"("*"),"method"["PUT"})

在这里你可以找到一篇关于它的文章。

最新更新