调用未定义的方法 Symfony\Component\HttpFoundation\Response::header()

2022-08-30 18:51:29

嗨,我正在使用一个cors中间件,它似乎工作正常,直到我添加Laravel护照现在有一个问题。它显示错误

 Call to undefined method Symfony\Component\HttpFoundation\Response::header() on line number 36 

这是我的中间件:

<?php

namespace App\Http\Middleware;

use Closure;
use Illuminate\Support\Facades\Response;

class Cors
{

    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {

// ALLOW OPTIONS METHOD
        $headers = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => "Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers"
        ];


        if ($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach ($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

}

问题是在if条件之后..任何帮助都会得到赞赏,谢谢


答案 1

嗨,我遇到了同样的问题。这似乎是Passport中的一个错误,并且有许多开发人员处于相同的情况。我刚刚找到了这个问题的解决方案。我们得到这个错误的原因是因为我们得到的响应对象通常是类的一个实例,我们可以使用该方法设置响应标头,而Passport处理的请求将是我们得到错误的原因middlewareIlluminate\Http\Responseheader('Header-Key', 'Header-Value')Symfony\Component\HttpFoundation\ResponseCall to undefined method Symfony\Component\HttpFoundation\Response::header()

以下是我用于解决此错误的代码,现在一切正常。我希望它能帮助其他开发人员了解如何修复它,然后适应他们的代码。

$response = $next($request);
$IlluminateResponse = 'Illuminate\Http\Response';
$SymfonyResopnse = 'Symfony\Component\HttpFoundation\Response';
$headers = [
    'Access-Control-Allow-Origin' => '*',
    'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, PATCH, DELETE',
    'Access-Control-Allow-Headers' => 'Access-Control-Allow-Headers, Origin,Accept, X-Requested-With, Content-Type, Access-Control-Request-Method, Authorization , Access-Control-Request-Headers',
];

if($response instanceof $IlluminateResponse) {
    foreach ($headers as $key => $value) {
        $response->header($key, $value);
    }
    return $response;
}

if($response instanceof $SymfonyResopnse) {
    foreach ($headers as $key => $value) {
        $response->headers->set($key, $value);
    }
    return $response;
}

return $response;

而在我的Kernel.php

protected $middleware = [
    \App\Http\Middleware\Cors::class,
    // ....
];

答案 2

似乎从您的应用程序中,您正在获得,它没有该方法。因此,您可以尝试将标头设置为 的变量。HttpFoundation\ResponseheaderheadersHttpFoundation\Response

foreach ($headers as $key => $value)
    $response->headers->set($key, $value);
return $response;

推荐