简体   繁体   English

Laravel 5.6 CORS问题

[英]Laravel 5.6 CORS issue

I followed this post but it only worked for GET method (as you can see it is mentioned in comments). 我关注了这篇文章,但它仅适用于GET方法(如您所见,已在注释中提及)。 I also installed this pakage but again it only works for GET method. 我也安装了此包装,但同样仅适用于GET方法。 This the error I get: 这是我得到的错误:

No 'Access-Control-Allow-Origin' header is present on the requested resource. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin my origin is therefore not allowed access. 因此,不允许访问我的起源 The response had HTTP status code 403. 响应的HTTP状态码为403。

PHP version: 7.1 PHP版本:7.1

Laravel version: 5.6 Laravel版本:5.6

Frontend application: angular app (Do I need to change sth here?) 前端应用程序: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,
];
}

you need use first method this post without use any package then add also this class to protected $middleware like this post then post method also have desired headers. 您需要不使用任何程序包情况下使用方法的第一个方法,然后再将此类添加到protected $middleware例如方法,然后post方法也具有所需的标头。

it works for me, I hope work for you. 它对我有用,我希望对你有用。

No need any type package for laravel-cors. laravel-cors不需要任何类型的软件包。 Just create Middleware: 只需创建中间件:

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

In app/Http/Kernel.php add Middleware in $middleware section: 在app / Http / Kernel.php中,在$ middleware部分中添加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
];

You could also use the great laravel-cors package by barryvdh. 您也可以使用barryvdh的laravel-cors软件包。

After you have the package installed, the easiest way to get CORS support for all your routes is to add the middleware like this in Http/Kernel.php: ($middleware) 安装软件包后,获得所有路线的CORS支持的最简单方法是在Http / Kernel.php中添加这样的中间件:($ middleware)

\Barryvdh\Cors\HandleCors::class

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM