Laravel 5:在尝试通过API访问数据时调用未定义的方法Response :: header()?

ano*_*nym 1 api access-control cors laravel-5

我使用带有CORS中间件的Laravel构建了一个API.

<?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');
    }
}
Run Code Online (Sandbox Code Playgroud)

当尝试通过API访问数据时localhost:8000/api/items,我在Laravel终端上获得以下URL

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

我错过了什么吗?

Gog*_*maT 6

我知道这有点晚了,但是在使用时我有类似的问题Symfony\Component\HttpFoundation\StreamedResponse.

正如你所说的问题是

调用未定义的方法... :: header()

很明显,该header方法不存在于对象上.

对我来说,解决方案是使用headers方法,它返回给你\Symfony\Component\HttpFoundation\ResponseHeaderBag.

像这样使用它:

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;
}
Run Code Online (Sandbox Code Playgroud)