0

I followed this post but it only worked for GET method (as you can see it is mentioned in comments). I also installed this pakage but again it only works for GET method. This the error I get:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin my origin is therefore not allowed access. The response had HTTP status code 403.

PHP version: 7.1

Laravel version: 5.6

Frontend application: angular app (Do I need to change sth here?)

//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,
];
}
Kasra GH
  • 157
  • 2
  • 5
  • 22
  • Install this package link "https://github.com/barryvdh/laravel-cors" and re-run the project by clear config, route. – Sachin Kumar May 29 '18 at 16:48
  • I mentioned the fact that I've already tested this package in the question. But I got the same error. – Kasra GH May 29 '18 at 16:49
  • Let do one more thing. Instead of adding * to origin add the url of your laravel application. And I expect you clear the cache, route and config of your laravel project – Sachin Kumar May 29 '18 at 16:51
  • I got the same error – Kasra GH May 29 '18 at 17:01
  • I have also set-up the project with same requirement. First time it gives me error but after re-run it works. Anyway could you please update your question with kernel.php and cors.php(config file) – Sachin Kumar May 29 '18 at 17:03
  • I added the ones you wanted – Kasra GH May 29 '18 at 17:11
  • You said you are using "\Barryvdh\Cors\HandleCors::class" package then why you need to create cors middleware? – Sachin Kumar May 29 '18 at 17:12
  • I tested two different methods. The first method is the one mentioned in another stackoverflow question ( but didn't work). The second method is using the laravel-cors package (didn't work either). – Kasra GH May 29 '18 at 17:13
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/172015/discussion-between-sachin-kumar-and-kasra-gh). – Sachin Kumar May 29 '18 at 17:14
  • I have a similar issue with Barryvdh\Cors package.The issue was Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://ip/upload. (Reason: expected ‘true’ in CORS header ‘Access-Control-Allow-Credentials’).I changed 'supportsCredentials' => true in config/cors.php.I think issue related to 'Orgin' is mentioned in laravel-cors/readme.md as a note. Note: If you are explicitly whitelisting headers, you must include Origin or requests will fail to be recognized as CORS. – Shaju Nr Jun 22 '18 at 05:35

3 Answers3

2

No need any type package for 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:

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
];
JJJ
  • 32,902
  • 20
  • 89
  • 102
1

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.

it works for me, I hope work for you.

PersianArt
  • 11
  • 2
0

You could also use the great laravel-cors package by barryvdh.

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)

\Barryvdh\Cors\HandleCors::class

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

More info check https://github.com/barryvdh/laravel-cors/blob/master/readme.md

  • Please read the question carefully. I mentioned that I've used this package and I got the same error. Only GET works – Kasra GH May 29 '18 at 18:53