Ap3twe's avatar

Larevel as a Bridge for React Cors Problem

Running to CORS header ‘access-control-allow-origin’ missing issues. Both the client and backend are subdomains. For the client, I use FormData. On Development, it works on localhost

Cors.php


    'paths' => ['api/newProspect', 'sanctum/csrf-cookie'],

    'allowed_origins' => ['https://internal.com', 'http://internal.com'],
    'allowed_methods' => ['GET, POST, PUT, DELETE, PATCH, OPTIONS'],
    'allowed_origins_patterns' => [],

    'allowed_headers' => ['Content-Type, X-Auth-Token, Authorization, Origin'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => false,

Kernel.php

    protected $middleware = [
        \Fruitcake\Cors\HandleCors::class,
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\CorsMiddleware::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

Controller

try {
    $response = Http::withHeaders([
        'Accept' => 'application/json',
        "X-DreamFactory-API-KEY" => env('REACT_APP_API_KEY'),
        "Access-Control-Allow-Origin"=> "*",
        "Access-Control-Allow-Methods"=>
        "GET, POST, PATCH, PUT, DELETE, OPTIONS",
        "Access-Control-Allow-Headers"=> "Origin, Content-Type, X-Auth-Token",
        "cors-enabled"=> false,
    ])->withOptions(
        [
                'Content-Type' => 'application/json',

        ]
    )->post($url, [

         "resource" =>  $data
        ]);
0 likes
4 replies
thinkverse's avatar

You have two cors middlewares attached, both Fruitcake and Laravel's own, try sticking to one of them since one could be adding headers and the other removing them.

// \Fruitcake\Cors\HandleCors::class,
// \App\Http\Middleware\TrustHosts::class,
\App\Http\Middleware\CorsMiddleware::class,
Ap3twe's avatar

@thinkverse I removed the file. That was a mistake on my part but it did not fixed it

Ap3twe's avatar

Guys, I have tried several fixes nothing works. I commented out fruitcake, and tried htaccess and the also index.php file in the public folder, I still get the cors header not available error problem

htaccess Acess example 1

<FilesMatch "\.(ttf|otf|eot|woff|woff2)$">
    <IfModule mod_headers.c>
        SetEnvIf Origin "http(s)?://(www\.)?(internal.group.com|localhost:8000|localhost:8080)$" 
        AccessControlAllowOrigin=
<IfModule mod_rewrite.c>
Header set Access-Control-Allow-Origin "*"
    <IfModule mod_negotiation.c>
        Options -MultiViews -Indexes
    </IfModule>
    RewriteEngine On
    # Handle Authorization Header
    RewriteCond %{HTTP:Authorization} .
    RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]

    # Redirect Trailing Slashes If Not A Folder...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_URI} (.+)/$
    RewriteRule ^ %1 [L,R=301]

    # Send Requests To Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>
Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin Header merge Vary Origin </IfModule> </FilesMatch>

htaccess example 2

$allowOrigins = array([
    'https://group.com',
    'http://internalprocess.group.com',
    'https://internalprocess.group.com',
    'http://internal.group.com',
    'https://internal.group.com',
    'http://localhost:8080',
    'http://localhost:8000',
    'http://localhost:3000',
]);

if (isset($_SERVER['HTTP_ORIGIN']) && ($_SERVER['HTTP_ORIGIN'] !== '')) {
  foreach ($allowOrigins as $allowOrigin) {
  if(preg_match( '*' . $allowOrigin . '*', $_SERVER['HTTP_ORIGIN'])) {
      header('Access-Control-Allow-Origin: ' . $_SERVER['HTTP_ORIGIN']);
     header('Access-Control-Allow-Credentials: true');
     header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS');
     header('Access-Control-Max-Age: 1728000');
     header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, X-Requested-With, X-CSRF-Token, ip, Content-Length, Content-Range, Content-Disposition, Content-Description'); 
    break;
    }
     
   }
   
}

index.php example 1

          header('Access-Control-Allow-Origin: https://internal.group.com');
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS, HEAD');
            header('Access-Control-Max-Age: 1728000');
            header('Content-Type: application/json');
            header('cors-enabled: false');
            header('mode: no-cors');
            header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token'); 

index.php example 2.

LARACASTS_SNIPPET_PLACEHOLDER
Ap3twe's avatar
Ap3twe
OP
Best Answer
Level 5

I solved it by adding the Access Origin in the htacess in the public folder. I commented out the fruitcake Cors in the kernal.php Midddleware array.

Add this in htacess

<ifModule mod_headers.c>
    Header set Access-Control-Allow-Origin: *
  </ifModule>

Kernal.php under App\Http

  protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \App\Http\Middleware\TrustProxies::class,
        //\Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

Please or to participate in this conversation.