【问题标题】:Laravel 5.6 CORS issueLaravel 5.6 CORS 问题
【发布时间】:2018-11-08 09:25:19
【问题描述】:

我关注了this post,但它只适用于 GET 方法(正如您在 cmets 中提到的那样)。我还安装了this pakage,但它只适用于 GET 方法。这是我得到的错误:

请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin my origin 因此不允许访问。响应的 HTTP 状态代码为 403。

PHP 版本:7.1

Laravel 版本:5.6

前端应用程序:Angular 应用程序(我需要在这里更改吗?)

//Cours.php (middleware I created myself using the first method)
class Cors
{
    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT,         
DELETE, OPTIONS');
    }
}


//cors.php (config/cors.php second method using the laravel-cors package)
return [

    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
];


//kernel.php
namespace App\Http;

use Illuminate\Foundation\Http\Kernel as HttpKernel;

class Kernel extends HttpKernel
{

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \Barryvdh\Cors\HandleCors::class,
];

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];


protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
    'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
    'can' => \Illuminate\Auth\Middleware\Authorize::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
    'cors' => \App\Http\Middleware\Cors::class,
];
}

【问题讨论】:

  • 安装此包链接“github.com/barryvdh/laravel-cors”并通过clear config, route重新运行项目。
  • 我提到了我已经在问题中测试过这个包的事实。但我得到了同样的错误。
  • 让我们再做一件事。而不是添加 * 到 origin 添加你的 laravel 应用程序的 url。我希望你清除你的 laravel 项目的缓存、路由和配置
  • 我遇到了同样的错误
  • 我也设置了具有相同要求的项目。第一次它给我错误,但重新运行后它可以工作。无论如何,您能否用 kernel.php 和 cors.php(config file) 更新您的问题

标签: php laravel cors


【解决方案1】:

laravel-cors 不需要任何类型的包。 只需创建中间件:

namespace App\Http\Middleware;
use Closure;
class Cors {

    public function handle($request, Closure $next) {
        $allowedOrigins = ['http://myroute.xyz', 'http://clarkconcepts.net','http://localhost'];
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        if (in_array($origin, $allowedOrigins)) {
            return $next($request)
                ->header('Access-Control-Allow-Origin', $origin)
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With, cache-control,postman-token, token')
                ->header('Access-Control-Allow-Credentials',' true');
        }
        return $next($request);
    }
}

在 app/Http/Kernel.php 在 $middleware 部分添加中间件:

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\Cors::class, //added here
];

【讨论】:

    【解决方案2】:

    您需要使用第一种方法 this post 而不使用任何包,然后将此类添加到 protected $middleware 就像 this post 然后 post 方法也有所需的标题。

    它对我有用,我希望对你有用。

    【讨论】:

      【解决方案3】:

      您也可以使用 barryvdh 提供的很棒的 laravel-cors 包。

      安装包后,为所有路由获取 CORS 支持的最简单方法是在 Http/Kernel.php 中添加这样的中间件:($middleware)

      \Barryvdh\Cors\HandleCors::class
      

      并编辑config/Cors.php'allowedOrigins' => ['*']

      更多信息查看https://github.com/barryvdh/laravel-cors/blob/master/readme.md

      【讨论】:

      • 请仔细阅读问题。我提到我已经使用了这个包,我得到了同样的错误。只有 GET 有效
      猜你喜欢
      • 1970-01-01
      • 2018-09-09
      • 2023-03-17
      • 2019-02-05
      • 1970-01-01
      • 2017-02-13
      • 2017-05-07
      • 2019-07-03
      • 2020-10-20
      相关资源
      最近更新 更多