如何解决Laravel中的'Access-Control-Allow-Origin'问题?

时间:2019-01-25 06:27:08

标签: php jquery laravel cors

我有一个Laravel项目,现在我需要一个图像下载功能来下载已经通过我的项目上传到亚马逊的图像。设置下载功能和下载按钮以下载特定图像后,控制台将显示以下错误。

无法加载'image-url':所请求的资源上没有'Access-Control-Allow-Origin'标头。因此,不允许访问源“ localhost-virtual-servel”。

这是从stackoverflow中找到的下载功能:

<a class="download-btn" data-href="image-url" download><span class="a2a_svg"></span></a>

function forceDownload(link){
    var url = link.getAttribute("data-href");
    var fileName = link.getAttribute("download");
    link.innerText = "Working...";
    var xhr = new XMLHttpRequest();
    xhr.open("GET", url, true);
    xhr.responseType = "blob";
    xhr.onload = function(){
        var urlCreator = window.URL || window.webkitURL;
        var imageUrl = urlCreator.createObjectURL(this.response);
        var tag = document.createElement('a');
        tag.href = imageUrl;
        tag.download = fileName;
        document.body.appendChild(tag);
        tag.click();
        document.body.removeChild(tag);
        link.innerText="Download Image";
    }
    xhr.send();
}

我创建了一个中间件,将“ Allow-access-control-Origin”标头设置为所有(*),如下所示

中间件:

<?php

namespace App\Src\Modules\Common\Middleware;

use Closure;

class cors {

    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        header("Access-Control-Allow-Origin: *");

        // ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
        ];
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

Kernal.php:

protected $routeMiddleware = [
        'cors' => \App\Src\Modules\Common\Middleware\cors::class,
    ];

路线:

Route::get('my_page', array('middleware' => 'cors', 'as'=>'my.page-get','uses'=>'MyController@getMyPage'));

但是错误仍然存​​在。我该如何解决?

2 个答案:

答案 0 :(得分:0)

尝试添加标题(“ Access-Control-Allow-Origin:*”);也在您的$ headers数组中。

答案 1 :(得分:0)

将此代码放在routes / api.php的顶部,或者如果您在routes / web.php中写了路由

 protected override async void OnSleep()
 {
 var minute = TimeSpan.FromSeconds(30);
 Device.StartTimer(minute, () =>
 { 
 await Task.Run(async () =>
 {
 TimeSpan t = TimeSpan.FromSeconds(10);
 var locator = Plugin.Geolocator.CrossGeolocator.Current;
 locator.DesiredAccuracy = 5;
 var position = await locator.GetPositionAsync(timeout: t); 
 //API Method
 });
 });
 }

对您来说很好。