Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel CORS middleware fails for post and resource request

I've been trying to solve this problem for a while, but unable to crack it.

I've a Laravel Backend and angular frontend. These are on different domains as the frontends need to be a web and mobile cordova app.

Even after adding CORS middleware, post and resource request fail to load and I get a

No 'Access-Control-Allow-Origin' header is present on the requested resource

error in console.

The following get request does work fine :-

Route::get('example', ['middleware' => 'cors', function(){
    return Response::json(array('name' => 'Steve Jobs 1', 'company' => 'Apple'));
}]);

But following ones fail -

Route::group(['middleware' => 'cors'], function () {
Route::group(['prefix' => 'api'], function()
{
    Route::resources('authenticate', 'AuthenticateController', ['only' => ['index']]);
    Route::post('authenticate', 'AuthenticateController@authenticate');
});
});

I am following https://scotch.io/tutorials/token-based-authentication-for-angularjs-and-laravel-apps.

My CORS.php

class CORS
{
/**
 * Handle an incoming request.
 *
 * @param  \Illuminate\Http\Request  $request
 * @param  \Closure  $next
 * @return mixed
 */
public function handle($request, Closure $next)
{
    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

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

kernel.php

class Kernel extends HttpKernel
{

protected $middleware = [
    \Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,
    \App\Http\Middleware\EncryptCookies::class,
    \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
    \Illuminate\Session\Middleware\StartSession::class,
    \Illuminate\View\Middleware\ShareErrorsFromSession::class,
    /*\App\Http\Middleware\VerifyCsrfToken::class,*/
];


protected $routeMiddleware = [
    'auth' => \App\Http\Middleware\Authenticate::class,
    'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
    'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
    'jwt.auth' => \Tymon\JWTAuth\Middleware\GetUserFromToken::class,
    'jwt.refresh' => \Tymon\JWTAuth\Middleware\RefreshToken::class,
    'cors' => 'App\Http\Middleware\CORS',
];
}
like image 933
Stacy J Avatar asked Nov 06 '15 14:11

Stacy J


1 Answers

Had the same problem for hours now. Tried different solutions (used the barryvdh/laravel-cors library, made my own CORS middleware, added headers in the index.php file) but nothing helped me out.

Now I'm using https://github.com/neomerx/cors-illuminate and it works.

One of the differences between the cors-illuminate library and the laravel-cors library is in the installation guide. At the cors-illuminate guide it explicitly says that you have to add the middleware line directly after

\Illuminate\Foundation\Http\Middleware\CheckForMaintenanceMode::class,

Maybe the laravel-cors library would work also, if you add the Middleware directly after the CheckForMaintenanceMode Middleware. Didn't try it out.

like image 150
Stefan Gi Avatar answered Oct 25 '22 05:10

Stefan Gi