使用以下代码从 url 下载图像时,我的 get 请求被 CORS 策略阻止:
await get(product.imageUrl).then((img) async {
print('image downloaded');
var dwnldProd = product;
dwnldProd.productImage = img.bodyBytes;
await _productRepository.saveProduct(dwnldProd);
}).catchError((e) {
print('downloading product image error: $e');
});
如 No 'Access-Control-Allow-Origin' header is present on the requested resource.
说我的请求缺少标题,所以我将它们添加为:await get(product.imageUrl, headers: <String,String>{
'Access-Control-Allow-Origin': '*', // Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
// 'Access-Control-Allow-Origin':'http://localhost:5000/', // Request header field access-control-allow-origin is not allowed by Access-Control-Allow-Headers in preflight response.
"Access-Control-Allow-Methods": "GET, POST, OPTIONS, PUT, PATCH, DELETE",
"Access-Control-Allow-Headers": "Origin, X-Requested-With, Content-Type, Accept"
}).then((img) async {
print('image downloaded');
var dwnldProd = product;
dwnldProd.productImage = img.bodyBytes;
await _productRepository.saveProduct(dwnldProd);
}).catchError((e) {
print('downloading product image error: $e');
});
但现在错误是 access-control-allow-origin is not allowed.
我在 SO 上从各种公认的答案中尝试了很多参数组合,但没有一个在我的情况下有效。你能发现我的标题有什么问题吗?
值得一提的是,我在 Chrome 上以 Release模式运行网络应用程序
使用命令
flutter run -d chrome --release --web-hostname localhost --web-port 5000
.非常感谢你的帮助。
更新
我注意到了这一点,但我不明白:
如果我供应
access-control-allow-origin
在请求 header 中,我收到错误 field access-control-allow-origin is not allowed
:但是如果我把它注释掉,那么错误就是
No 'access-control-allow-origin' header is present on the requested resource
:由于资源是 firebase 存储上的文件,我是否应该在上传图像时在资源上创建这个未找到的 header ?
如果是怎么办?也许在元数据中?
最佳答案
终于找到问题所在了。
事实上,我被阅读错误误导了。而field x is no allowed in headers
很清楚,我误读了 No 'access-control-allow-origin' header is present on the requested resource
.并认为我的请求缺少 header ..所以当最终正确阅读 on requested resources
我意识到我没有对存储桶做任何事情:
我必须为我的 Google Storage 存储桶设置 CORS。
因此,按照文档中的说明使用 gustily 非常简单。
google_storage_cors.json
带有颤动的文件,其中包含:[
{
"origin": ["*"],
"method": ["GET"],
"responseHeader": ["Access-Control-Allow-Origin"],
"maxAgeSeconds": 3600
}
]
哪里["*"]
将针对您的域进行更改,对于本地主机部署,它非常完美.. []
除了 maxAgeSeconds 之外的所有其他人都需要..gsutil cors set [filepath] [your bucket]
将其上传到 Google Storage gut get [your bucket]
检查它是否已上传。 特别感谢他给了-1。看到乐于助人的人总是很高兴。
干杯。
希望这对第一次处理这个问题的人有所帮助,并且在理解错误和找到解决方案方面有很多困难。
关于get - access-control-allow-origin is not allowed 错误,但如果省略则预期从获取请求 Flutter web,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62892376/