anonym
anonym

Reputation: 4850

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?

Upvotes: 4

Views: 7094

Answers (2)

Olvis Quintana
Olvis Quintana

Reputation: 79

try by this way , this should fix your CORS issues, declaring it into your class's constructor. and it will let you API work.

<?php

namespace App\Http\Middleware;

use Closure;

class Cors
{

   public function __construct(Request $request) {

        $request->header('Access-Control-Allow-Origin', '*');
        $request->header('Content-Type', 'text/plain');
    }
}

why people is voting negative to this answer ? this work aswell and fine than others , im currently using in a production site , i was the first solution answer for the guy that request for that help intime.

Upvotes: 0

GogromaT
GogromaT

Reputation: 511

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;
}

Upvotes: 18

Related Questions