在调用图像时,Cors Origin在laravel的Direct Path中

时间:2017-03-26 10:50:05

标签: php laravel angular cors virtual-reality

现在我使用laravel 5.2作为webserivce和angular2作为首页构建Web应用程序 我使用来自http://cdn.pannellum.org的VR库 我的问题当我从mywebsite.com/public/Images/photo7.png我的数据库中调用Iamge链接时 给我回复此消息

  

'访问控制允许来源'标题出现在请求的上   资源。起源' http://localhost:5565'因此是不允许的   访问。

但我在开始项目从laravel和angular传输数据之前处理了这个问题但是当我从直接路径调用我的图像时返回给我这条消息

2 个答案:

答案 0 :(得分:1)

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 request

您还可以阅读this answer以避免可能导致CORS错误的其他问题。

答案 1 :(得分:0)

尝试以下方法:

  1. enter link description here安装和配置Cors
  2. 添加Cors模式
fetch(url,{mode:"cors"})
                    .then(res => res.blob())
                    .then(blob => {
                        const file = new File([blob], 'dot.png', {type:'image/png'});
                        console.log(file);
                    });
  1. 来自enter link description here的资源