Laravel CORS with Fruitcake
Asked Answered
U

5

9

I make react project with laravel Back-end ... I have a CORS problem, I do everything like on link below, with fruitcake.

Laravel 6 CORS policy issue with API but still not working.

cors.php:

        'paths' => ['api/*'],

    /*
    * Matches the request method. `[*]` allows all methods.
    */
    'allowed_methods' => ['*'],

    /*
     * Matches the request origin. `[*]` allows all origins.
     */
    'allowed_origins' => ['*'],

    /*
     * Matches the request origin with, similar to `Request::is()`
     */
    'allowed_origins_patterns' => [],

    /*
     * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers.
     */
    'allowed_headers' => ['*'],

    /*
     * Sets the Access-Control-Expose-Headers response header.
     */
    'exposed_headers' => false,

    /*
     * Sets the Access-Control-Max-Age response header.
     */
    'max_age' => false,

    /*
     * Sets the Access-Control-Allow-Credentials header.
     */
    'supports_credentials' => false,

And, kernel middle-ware is:

        protected $middleware = [
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\CheckForMaintenanceMode::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,

        \Fruitcake\Cors\HandleCors::class,
    ];

what else could be the problem?

Urea answered 11/2, 2020 at 11:41 Comment(0)
E
12

Here are some gotchas when using fruitcake/laravel-cors:

  • Put HandleCors middleware at the top of $middleware in app/Http/Kernel.php:
protected $middleware = [
    \Fruitcake\Cors\HandleCors::class,
    \App\Http\Middleware\TrustProxies::class,
    \App\Http\Middleware\CheckForMaintenanceMode::class,
    \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
    \App\Http\Middleware\TrimStrings::class,
    \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
];

Putting it at the bottom or somewhere between won't work because requests might be rejected by other middlewares with higher priority.

  • Do NOT die or exit in controller.

For example the following won't work:

Route::get('/cors-test', function() {
   dd("This won't work");
});

Because Fruitcake\Cors\HandleCors::handle method adds relevant headers AFTER handling request:

Fruitcake\Cors\HandleCors.php

public function handle($request, Closure $next)
{
    // --- omitted

    // Handle the request
    $response = $next($request); // <--- if you die here

    if ($request->getMethod() === 'OPTIONS') {
        $this->cors->varyHeader($response, 'Access-Control-Request-Method');
    }
    
    // you will never reach here
    return $this->addHeaders($request, $response);
}

dump does not work either

  • Clear config cache after changing app/config/cors.php:
$ php artisan config:cache
Escobar answered 16/9, 2020 at 5:43 Comment(2)
In my case was a dump in a FormRequest methodTripod
In my case it was the redirect from www. to non-www, I was making a request to www version which converted POST requests to GETFreespoken
D
4

The Fruitcake\Cors\HandleCors::class is troublesome. Just remove it from everywhere and add these 3 headers in api.php route file on the top.

header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length');
header('Access-Control-Allow-Origin: *');
Delighted answered 29/8, 2020 at 19:7 Comment(5)
can you tell us why it is "troublesome"? Your solution does not handle preflights correctlyGoober
It comes with a route middleware registered as cors. Right? So what is a good idea to use it. By putting it as a route or routegroup middleware. It just fails to add the required headers until you add it to the global middleware in the kernel file.Delighted
ok, but that is the laravel way to do it. Btw laravel 7 uses the fruitcake component as default, so there is no reason to avoid it. The way you do it will probably give an 404 on preflights, so this is not a solution.Goober
I also worked with it on laravel 7 itself. In my case I tried like everything. But it didn't work. So if you have it working, please post an answer.Delighted
Thanks @AnkitSingh. Your solution works for me and the fruitcake thingy was indeed the culprit.Gomes
C
-1
php artisan config:clear
php artisan route:clear
php artisan cache:clear

Make sure your permissions are setup correctly (eg. storage is writable)

Coquina answered 2/4, 2020 at 23:27 Comment(0)
K
-1

Actually ,just remove dd and die command from you code.

Kataway answered 31/3, 2021 at 11:53 Comment(1)
Thanks for your answer. In fact, that's what @bravemaster already pointed out and on the other hand I can't see the thread owner doing dd() or die() in any of the code samples.Audriaaudrie
M
-2

Add credentials: 'same-origin' to your request header in the react App

Mignon answered 23/12, 2020 at 0:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.