kumar92varun
1 year ago

CORS Access-Control-Allow-Origin headers not being added in api subdomain

Posted 1 year ago by kumar92varun

I am creating a multi-sub-domain web application using Laravel 5.5 with 3 sub-domains right now:- store.example.com admin.example.com api.example.com

Since store.example.com and admin.example.com need to interact with api.example.com for all the back-end operations via jQuery AJAX, I need to add a "Access-Control-Allow-Origin" header on all requests of api.example.com

I created a middleware in /app/Http/Middleware/CORS.php with the following content:-

<?php

namespace App\Http\Middleware;
use Closure;
class CORS
{
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin' , '*');
        $response->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
        return($response); 
    }
}
?>

And registered it in /app/Http/Kernel.php under:-

protected $middleware = [
    ...
    ...
    ...
    \App\Http\Middleware\CORS::class,
];

I have also disabled the VerifyCsrfToken Middleware from Kernel. I don't want to use CSRF protection, at least for now.

The main issue is that my store and admin sudbomain are successfully having the above headers on all GET / POST requests, but not the api subdomain. Don't know what's wrong, but api subdomain won't add these headers in any of it's GET or POST request.

Can someone please tell me what's going wrong in adding the above headers in api subdomain particularly when it's working great with every other subdomain?

Thanks.

Please sign in or create an account to participate in this conversation.