I built an API with Laravel with a CORS middleware.
<?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-XSRF-TOKEN');
}
}
When trying to access data via API, localhost:8000/api/items
, I get the following URL on my Laravel terminal and
Call to undefined method Symfony\Component\HttpFoundation\Response::header()
Am I missing something?
I know it's kind of late, but I had similar issue when using the Symfony\Component\HttpFoundation\StreamedResponse
.
As you said the problem was the
Call to undefined method ... ::header()
So clearly the header
method is not present on an object.
For me the solution was to use headers
method, which returns you the \Symfony\Component\HttpFoundation\ResponseHeaderBag
.
Use it like so:
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-XSRF-TOKEN');
return $response;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With