请求cloudinary资源会导致CORS错误

时间:2018-05-14 13:30:37

标签: php laravel cors cloudinary

我有一个laravel / lumen服务器来管理我的云资源的上传。我还将服务器用作我的前端应用程序的API端点。其中一个端点从Cloudinary返回一个文件。我通过将请求重定向到Cloudinary资源来实现此目的。但是我的应用程序失败了,因为重定向资源上没有CORS头。

return redirect()->to("https://res.cloudinary.com/gates/raw/upload/" . $upload->id);

我得到的错误是:

Redirect from 'https://{my-server.com}/api/v1/export' to 
'https://res.cloudinary.com/gates/raw/upload/{upload-id}' has been 
blocked by CORS policy: No 'Access-Control-Allow-Origin' header is 
present on the requested resource. Origin 'https://{my-frontend.com}' 
is therefore not allowed access.

2 个答案:

答案 0 :(得分:0)

您可以在服务器上使用此库:https://github.com/barryvdh/laravel-cors

return [
     /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
     | to accept any value.
     |
     */
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
    'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [],
    'maxAge' => 0,
]


allowedOrigins => [*] mean that you give access to your server, you can add ip's or dns for restrict access to your server

答案 1 :(得分:0)

  

这是我的CORS中间件:

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;
    }

}
  

要使用CORS中间件,您必须先在您的中间注册   app \ Http \ Kernel.php这样的文件:

protected $routeMiddleware = [
        //other middlewares
        'cors' => 'App\Http\Middleware\CORS',
    ];
  

然后你可以在路线中使用它

Route::get('example', array('middleware' => 'cors', 'uses' => 'ExampleController@dummy'));