现在我使用 Laravel 5.2 作为 Web 服务,使用 Angular2 作为首页构建 Web 应用程序 我使用来自 http://cdn.pannellum.org 的 VR 库 当我从我的数据库中调用 Iamge 链接(如 mywebsite.com/public/Images/photo7.png)时,我的问题 返回此消息给我
请求中存在“Access-Control-Allow-Origin”标头 资源。因此不允许使用 'http://localhost:5565' 访问。
但是我在开始项目从 Laravel 和 Angular 传输数据之前处理了这个问题,但是当我从直接 Path 调用我的图像时,返回给我这条消息
Laravel 5 (L5):在我的项目中,当我返回图像(文件)并想要避免 CORS 时,我使用以下代码(我在没有测试的情况下手动更改了它,但它应该可以工作):
private function responseFile($filePath, $fileMimeType, $originalFileName) {
$headers = array(
'Content-Type' => $fileMimeType,
//'Content-Disposition' => 'attachment; filename="'. $attachment->org_name . '"', - this header is added automaticaly
"Access-Control-Allow-Origin" => request()->getSchemeAndHttpHost() // allow CORS (e.g. for images)
);
return response()->download($filePath, $originalFileName, $headers);
}
在此解决方案中,您根本不需要接触 apache .htaccess 文件(或 nginx 配置文件)(如果这样做,将会导致标头重复错误) - 因为在这种情况下,我们使用所谓的 Simple CORS请求.
您还可以阅读此答案,以避免其他可能导致 CORS 错误的问题。
Laravel 9: 当图像未在 Flutter 应用程序上加载时,我遇到了同样的问题。 在公共文件夹外的根目录上添加这些行 .htaccess 文件:
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods "GET, POST, OPTIONS"
Header set Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range"
Header set Access-Control-Expose-Headers "Content-Length,Content-Range"
在 Config cors 中添加这些行:
{ 'paths' => ['api/*', 'sanctum/csrf-cookie','public/storage/images/*','/public/storage/images/*'],
}
在 ubuntu 服务器上运行此命令:
{ sudo a2enmod headers }