2

I'm using Laravel 5.6 and this Middleware to allow Ionic app call my API's

<?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, PATCH, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With, X-XSRF-TOKEN');
    }
}

So this is causing error for two requests where I'm forcing file download.

Call to undefined method Symfony\Component\HttpFoundation\BinaryFileResponse::header()

My request 1

return Excel::download(new \App\Exports\FleetExport($fleetId), 'debts.xlsx');

My request 2

return \Response::download($file_path,
                           $file_name,
                           array('Content-Type: application/octet-stream','Content-Length: '. filesize($file_path))
                           )->deleteFileAfterSend(true);

Disabling this middleware makes my requests works fine.

Am I doing something wrong?

1 Answer 1

5

You can try to adjust your middleware to set the headers on the header bag of the Response directly:

$response = $next($request);

$response->headers->add([
    'Access-Control-Allow-Origin' => '*',
     ...
]);

return $response;

All the responses that come through should extend from the base Symfony Response which has a public $headers property that is a HeaderBag. So this should work for all the responses.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.