Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5: Call to Undefined Method Response::header() when trying to access data through API?

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?

like image 429
anonym Avatar asked Oct 15 '25 12:10

anonym


1 Answers

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;
}
like image 177
GogromaT Avatar answered Oct 18 '25 02:10

GogromaT



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!