我正在开发Angular应用,以显示Google云存储桶的内容。对于背面,我在nodeJS中使用Google云功能
正如他们在文档中提到的上传文件一样,我创建了一个函数来生成签名的url,但是当我使用签名的url发送文件时,在浏览器中出现cors错误
我与邮递员测试,它会上传一个空文件
这是我的lambda函数:
// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');
// Creates a client
const storage = new Storage();
exports.generateSignedUrl = (req, res) => {
// generate signed url to use for file upload
const filename = req.query.fileName;
console.log('filename ', filename);
const filetype = req.query.fileType;
console.log('filetype ', filetype);
const bucketName = 'nx-terega-omega';
res.set('Access-Control-Allow-Origin', "*");
res.set('Access-Control-Allow-Headers', "Origin, X-Requested-With,
Content-Type, Accept, Authorization");
if (req.query.fileName !== null && req.query.fileName !== undefined
&& req.query.fileType !== null && req.query.fileType !== undefined)
{
generateV4UploadSignedUrl(bucketName, filename).then(function (value)
{
console.log('File Url response ', value);
res.status(200).send(JSON.stringify({'url': value}));
}).catch(error => {
res.status(404).send('Error while generating signed url');
});
} else {
res.status(500).send('Filename not found');
}
};
async function generateV4UploadSignedUrl(bucketName, filename, filetype) {
// [START storage_generate_upload_signed_url_v4]
// These options will allow temporary uploading of the file with outgoing
// Content-Type: application/octet-stream header.
const options = {
version: 'v4',
action: 'write',
expires: Date.now() + 15 * 60 * 1000, // 15 minutes
contentType: filetype,
};
// Get a v4 signed URL for uploading file
const [url] = await storage
.bucket(bucketName)
.file(filename)
.getSignedUrl(options);
console.log('Generated PUT signed URL:');
console.log(url);
console.log('You can use this URL with any user agent, for example:');
console.log("curl -X PUT -H 'Content-Type: application/octet-stream' " +`--upload-file my-file '${url}'`);
return url;
// [END storage_generate_upload_signed_url_v4]
}
当我收到签名的URL时,会将其发送到我的文件中,但它会返回
No 'Access-Control-Allow-Origin' header is present on the requested resource.
答案 0 :(得分:1)
签名的URL使用GCS的XML API。该API允许跨域请求,但默认情况下不启用它。您需要为存储桶指定CORS策略。
例如,您可以创建如下的CORS策略(假设这是一个名为policy.json
的文件):
[
{
"origin": ["http://example.appspot.com"],
"responseHeader": ["Content-Type"],
"method": ["GET", "HEAD", "DELETE"],
"maxAgeSeconds": 3600
}
]
以下是CORS政策文件的完整说明:https://cloud.google.com/storage/docs/xml-api/put-bucket-cors#request_body_elements
现在让我们将该策略应用于存储桶:
gsutil cors set policy.json gs://my-bucket-name
文档中有更多有关在存储桶上启用CORS的说明:https://cloud.google.com/storage/docs/configuring-cors
答案 1 :(得分:1)
如 Brandon Yarbrough 响应中所述,我必须在Google Cloud中配置cors。我在配置中丢失了一些东西
[
{
"origin": ["http://example.appspot.com"],
"responseHeader": ["*"],
"method": ["GET", "HEAD", "DELETE", "PUT"],
"maxAgeSeconds": 3600
}
]
您应该在{{1}中加入PUT
,并在method
中放入*
,因为responseHeader
不够