0

I built Laravel APIs and hosted on namecheap. I have set up the handleCORS file with these attributes:

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

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => ['*'],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => true,

On the frontend, my requests are made using axios with the only header set being the content-type: application/json. Making a request when the server was on localhost works fine. But pushing to namecheap and pushing the frontend to vercel, I keep getting this error:

Access to XMLHttpRequest at 'https://landearn.bumasys.com/api/signup' from origin 'https://landearn-web.vercel.app' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

And these are my response headers:

     cache-control: private, no-cache, no-store, must-revalidate, max-age=0
     content-length: 1238
     content-type: text/html
     date: Tue, 14 Sep 2021 09:49:28 GMT
     pragma: no-cache
     server: LiteSpeed
     x-turbo-charged-by: LiteSpeed

The problem is that I have tried so many solutions, used a custom CORS middleware with these configurations:

$headers = [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers'=> 'Authorization, Content-Type, X-Auth-Token, Bearer, Origin',
            'Cache-Control' => 'no-cache, private',
            'X-RateLimit-Limit' => '60',
            'X-RateLimit-Remaining' => '59',
        ];
        
        return response('OK', 200, $headers);
        
        if($request->getMethod() == "OPTIONS") {
            // The client-side application can set only headers allowed in Access-Control-Allow-Headers
            return response('OK', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
            $response->header($key, $value);
        return $response;

I even added a preflight middleware that captures every OPTIONS request and sends an empty response to the browser requesting resource, here:

public function handle($request, Closure $next )
{
    if ($request->getMethod() === "OPTIONS") {
        return response('');
    }
    return $next($request);
}

Have I sought for solutions, yes I have. I don't know why this is happening, and in time past I have been restricted to using only one Laravel application I configured back then for my API requests, but it's too clustered and not good enough for me to continue using, funny part is that if I reproduce that same project into another domain by zipping and extracting it, I still get the same CORS problem, am now really lost on how to permanently fix this CORS madness, I really can't continue this way.

optimalresource
  • 168
  • 1
  • 12
  • Did you tried to set it like `header("Access-Control-Allow-Origin: *");` – fatm Sep 14 '21 at 10:25
  • I tried that and it didn't yield any fruit, I also noticed that it was irrelevant to make that specification from the client-side when making requests, as it is the sole function of the resource from where the response is expected. – optimalresource Sep 14 '21 at 10:26
  • In which server your project running at? You put directly in nginx or apache config – fatm Sep 14 '21 at 10:29
  • The server is running on Namecheap – optimalresource Sep 14 '21 at 10:29
  • [https://www.namecheap.com/support/knowledgebase/article.aspx/9410/29/how-to-set-up-rules-and-redirects-in-htaccess/](https://www.namecheap.com/support/knowledgebase/article.aspx/9410/29/how-to-set-up-rules-and-redirects-in-htaccess/) // [https://stackoverflow.com/a/20838470/10828488](https://stackoverflow.com/a/20838470/10828488) – fatm Sep 14 '21 at 10:32
  • There can be a server restrictions so i think you should configure server config – fatm Sep 14 '21 at 10:33
  • Am really trying to setup the server, still nothing. May end up trying Heroku instead of Namecheap. – optimalresource Sep 14 '21 at 10:50

1 Answers1

0

I noticed that any of the previous solutions I found and tried implementing during my research was good enough to handle the cross origin resource sharing issues, but the htaccess was the main problem. So I was able to use the correct htaccess inside my server root as shown below:

<IfModule mod_rewrite.c>
    <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>

Also, having implemented the change, I noticed that it wasn't necessary to build custom CORS files and change the configurations in the App\HTTP\kernel.php and App\Providers\RouteServiceProvider.php, so using the current package that comes with Laravel, the \Fruitcake\Cors\HandleCors::class, it is sufficient enough to solve the problem of strict-origin-when-cross-origin error from preflight. But you will need to tweak the config\cors.php file with the following values;

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

    'allowed_methods' => ['*'], 

    'allowed_origins' => ['*'], /*very necessary, else specify the exact domain prefix or suffix*/

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => ['*'], /*added this to be able to see the response headers*/

    'max_age' => 0,

    'supports_credentials' => false, /*leaving this as false is better for a long life in good health*/

These are my few findings, and I felt it could be helpful to others in the future.

optimalresource
  • 168
  • 1
  • 12