Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

bvfi-dev's avatar

Simple Laravel API (With no Authentication) gets CORS blocked

I have the following installed: Laravel 11, Livewire 3, Jetstream 5 I have a simple Laravel controller:

class TestController extends Controller
{
    public function index(){
        $data= TestTable::all();
        return response()->json($data);
}

I then have created a Cors Middlware in Http/Middleware for Laravel:

class Cors
{
    public function handle(Request $request, Closure $next)
    {
        if ($request->isMethod('OPTIONS')) {
            return response()->json('{"method":"OPTIONS"}', 200, $this->getHeaders());
        } else {
            $response = $next($request);
            foreach ($this->getHeaders() as $key => $value) {
                $response->header($key, $value);
            }
            return $response;
        }
    }

    private function getHeaders(): array
    {
        return [
            'Access-Control-Allow-Origin' => '*',
            'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS',
            'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With, X-CSRF-Token',
        ];
    }
}

I then use this in my routes/web.php to make a new middleware group for the Cors file (Its a group, because I want to have multiple routes later on with the same Cors:

Route::middleware([Cors::class])->group(function () {
    Route::get('/apitest', [\App\Http\Controllers\TestController::class, 'index'])->name('apitest.index');

Then on my other website I call for the API like so:

try {
            const response = await fetch('https://laravel-page.plesk.page/apitest', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json',
                }
            });
        } catch (error) {
            return `<p>Failed to load branches. Error: ${error.message}</p>`;
        }

Which throws me the error Access to fetch at 'https://laravel-page.plesk.page/apitest' from origin 'https://www.other-website.de' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled. My goal is to simply have a connection, the page doesnt need authorization, it just returns a json response, that all I need for now. The real problem comes when I test it on POSTMAN. I literally just put my Laravel URL and change the request to GET and I get a 200 response, with what I need. So, postman works and here's the default pre-set headers there:

Cookie: XSRF-TOKEN=<random stuff in here > //I havent inserted this here, it was generated automatically by POSTMAN, I have only pasted the URL and changed to GET and I get 200 on send
Postman-Token: <calculated when request is sent>
Host: <calculated when request is sent>
User-Agent: PostmanRuntime/7.34.0
Accept: */*
Accept-Encoding: gzip, deflate, br
Connection: keep-alive

I dont think there's something wrong with my Laravel thing, but I dont even know what to change or where to look, the other site is a Ionos website, which is basically like WordPress and I insert the code there by simply adding a HTML element and pasting HTML and JS in there. If Postman works, then surely means I have to change the JS code, but I want to know how to allow Cors Origin directly from Laravel and my frameworks

0 likes
7 replies
bvfi-dev's avatar

@martinbean Nope, its still blocked, in the return array of cors.php, I have:

'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_methods' => ['*'],
    'allowed_origins' => ['*'],
    'allowed_origins_patterns' => [],
    'allowed_headers' => ['*'],
    'exposed_headers' => [],
    'max_age' => 0,
    'supports_credentials' => false,

I have cleared the cache with php artisan optimize:clear, moved my route outside any route groups (It didnt work, I then tried moving it inside Route::middleware([ 'auth:sanctum', config('jetstream.auth_session'), 'verified',])->group(function () {, it didn't work. This is now getting extremely frustrating. I dont know where to look or even how to debug this issue, could you please provide me steps as to how I can pinpoint this issue? Is it possible to make a Test?

krisi_gjika's avatar

@bvfi-dev your route is apitest but the cors.php allows api/* which does not match your route.

1 like
bvfi-dev's avatar

@krisi_gjika Thank you for this, I have switched things around, but I still get the same error. My route is no longer in my web.php, its in the api.php

martinbean's avatar

@bvfi-dev Have you actually checked the response to see if it contains the header (Access-Control-Allow-Origin) your JavaScript says is missing? Because if it is, then it sounds like your server is stripping those headers. In which case, you need to speak to your web host; not create “custom” middleware to do exactly what Laravel does and get the same result.

1 like
puklipo's avatar

The default CORS setting for Laravel 11 is "Allow all requests to api/* from any domains."

  1. Create new Laravel11 project
  2. php artisan install:api
  3. Use routes/api.php

The mistake is using routes/web.php

1 like
bvfi-dev's avatar

Thanks everyone for the responses, but the issue is still persisting, I have since edited my code:

bootstrap/app.php

return Application::configure(basePath: dirname(__DIR__))
    ->withRouting(
        web: __DIR__.'/../routes/web.php',
        api: __DIR__.'/../routes/api.php',
        commands: __DIR__.'/../routes/console.php',
        health: '/up',
    )
    ->withMiddleware(function (Middleware $middleware) {
        //        $middleware->append(Cors::class); //I have tried with and without this, this SHOULD apply the middleware on each request according to Laravel docs, but it doesn't
        $middleware->alias([
            'cors' => Cors::class,
        ]);
    })
    ...

Then in my api.php I have:

Route::get('/apitest', [TestController::class, 'index'])->middleware(['cors'])->name('apitest.index');

I have also tried making this rounte without any middleware, nothing changed. I then use the link /api/apitest. In Postman, I get the query in a JSON array, however, on the other website, where Im calling the api from, I still get the same error. At this point, I think I need to look into my server configuration (.htaccess) and try changing things there, my website is hosted on Plesk, so If anyone has any advice for how to do that for laravel there, Id greatly appreciate it.

1 like

Please or to participate in this conversation.