Laravel Cors

Hello. I am trying to do a crossdomain ajax request from my main domain to http://api.domain.uk (my API domain).

I am receiving (On the client side, when the ajax has been send): Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

What have I tried?<br>

I tried using header() in my index.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS, HEAD');
header('Access-Control-Allow-Headers: origin, Content-Type, Authorization, accept, soapaction, X-CSRF-Token');
header('Access-Control-Max-Age: 2000');

I tried making a middleware:

return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');

And now I am trying to use this: https://github.com/barryvdh

Using: https://github.com/barryvdh

I am also using Laravel 5.4 on IIS, with php 7

I have been trying to get this to work for multiple days, what is the issue?

Have I found anything works? Yes, putting all the headers in web.config works, but I don't want to do that for multiple reasons. It'll enable it on all domains of my Laravel project, along with multiple other reasons.

Routing (web.php):

Route::group(['domain' => 'api.domain.uk', 'namespace' => 'Api'], function() {
    Route::group(['middleware' => 'cors', 'prefix' => 'ajax'], function() {
        Route::get('/rooms/{id}/get-locked-status', [email protected]');
        Route::any('/rooms/{id}/update-locked-status', [email protected]');
    });
});

Middlewares:

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
        \Barryvdh\Cors\HandleCors::class,
    ],

    'api' => [
        'throttle:60,1',
        'bindings',
    ],
];

Cors config:

<?php
return [
     /*
     |--------------------------------------------------------------------------
     | Laravel CORS
     |--------------------------------------------------------------------------
     |
     | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
     | to accept any value.
     |
     */
    'supportsCredentials' => false,
    'allowedOrigins' => array('*'),
    'allowedHeaders' => array('*'),
    'allowedMethods' => array('*'), // ex: ['GET', 'POST', 'PUT',  'DELETE']
    'exposedHeaders' => [],
    'maxAge' => 0,
];

JS (Client side):

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

function toggleDoors(roomId) {
    $.ajax({
        url: 'http://api.domain.uk/ajax/rooms/' + roomId + '/update-locked-status',
        type: "GET",
        error: function(req, message) {
            alert('Error: ' + message);
        },
        success: function(data) {
            showNotification(data);
        },
    });
}

function showNotification(notificationText) {
    var notificationArea = $('#notification_area');
    var notification = $("<div>").addClass("ajax-alert success").html(notificationText);

    notification.appendTo(notificationArea);
    notification.delay(1000).fadeOut('slow');
}

Can anyone help me with this?

Seriosk
Seriosk
  • 1 week ago

On Laravel, you should never call the global header function. You must use the object oriented interface.

Also, the first result on Google for "Laravel cors" is. https://github.com/barryvdh/laravel-cors