LaravelでCall to undefined methodエラーが出る

2020年3月31日火曜日

Laravel

t f B! P L

Laravelで次のようなコードを書いて、ファイルをダウンロードしようとしたところ、" Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()"というエラーが発生しました。

    public function get_current_image()
    {
       $file = public_path('detected').'/frame_000.png';
       write_log(LOG_INFO,'file = '.$file);
       $mime_type = File::mimeType($file);
       $headers = [
           'Content-type' => $mime_type
       ];
       return response()->download($file,'frame_000.png',$headers);
    }

原因

次のような自作のCorsミドルウェアをプロジェクトに追加していたのをすっかり忘れていました。このミドルウェアを削除すると意図どおりに動作するようになりました。

<?php

namespace App\Http\Middleware;

use Closure;
class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type');
    }
}

このブログを検索

QooQ