问题描述
我正在尝试从 React 应用程序将文件上传到 Google 云存储的存储桶。我已为存储桶启用 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: This link 表示 URL 的形成存在问题,但我从谷歌云存储 NPM 包中获取该 URL 作为预签名 URL。顺便说一句,我已经按照 this link 设置了机制,但似乎我遗漏了一些非常明显的东西。
解决方法
抱歉我的回复延迟了。我注意到你的代码中有一些奇怪的东西。您的 JSON 文件中有此配置
[]
但是,在您的反应客户端中,您有这个
headers: {
// Accept: file.type,'Content-Type': file.type,'Access-Control-Allow-Origin': '*',}
如果您的 JSON 文件中有 [],则 you are removing CORS from a bucket。尽管如此,您仍在发送值。您需要将此添加到您的 JSON 文件中以在您的存储桶中设置 CORS。
[ { “起源”: [”*”], “方法”:[“PUT”] } ]
Here 你可以找到一篇关于它的文章。