Seb*_*i55 19 php http symfony laravel
我有以下问题:我想在路由上返回一个Image/getImage/{id}该函数如下所示:
public function getImage($id){
   $image = Image::find($id);
   return response()->download('/srv/www/example.com/api/public/images/'.$image->filename);
}
当我这样做时它返回给我:
FatalErrorException in HandleCors.php line 18:
Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()
我有use Response;控制器的开头.我不认为HandleCors.php是问题,但无论如何:
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Contracts\Routing\Middleware;
use Illuminate\Http\Response;
class CORS implements Middleware {
public function handle($request, Closure $next)
{
      return $next($request)->header('Access-Control-Allow-Origin' , '*')
            ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
     }
}
我实际上不知道为什么会发生这种情况,因为它与Laravel Docs中描述的完全相同.我收到错误后更新了Laravel,但这并没有解决它.
tre*_*ace 43
问题是你正在调用->header()一个Response没有该函数的对象(Symfony\Component\HttpFoundation\BinaryFileResponse该类).该->header()函数是Laravel的Response类使用的特征的一部分,而不是基本的Symfony Response.
幸运的是,您可以访问该headers属性,因此您可以这样做:
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin' , '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
return $response;
Mar*_*ton 12
您可能希望file通过检查header返回的Closure.
文件下载请求通常会从 中header省略该方法Closure。
public function handle($request, Closure $next)
{
    $handle = $next($request);
    if(method_exists($handle, 'header'))
    {
        $handle->header('Access-Control-Allow-Origin' , '*')
               ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')
               ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
    }
    return $handle;
    
}
如果您需要为file请求设置标头(如其他答案所建议的那样)$handle->headers->set()可以在else条件中使用:
public function handle($request, Closure $next)
{
    $handle = $next($request);
    if(method_exists($handle, 'header'))
    {
        // Standard HTTP request.
        $handle->header('Access-Control-Allow-Origin' , '*');
        return $handle;
    }
    // Download Request?
    $handle->headers->set('Some-Other-Header' , 'value')
    return $handle;
    
}
| 归档时间: | 
 | 
| 查看次数: | 12489 次 | 
| 最近记录: |