amiralidev
amiralidev

Reputation: 31

Laravel - React has been blocked by CORS policy

I built an API with Laravel and uploaded it into the Linux sharing host and when I want to use API with my React SPA. It works perfectly but this time I uploaded my API Laravel source to a Centos server in a folder of my domain and when I want to connect to the API with my React SPA, Chrome says:

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 when I add these codes to htaccess:

Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

the error changes to:

Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

I have installed https://github.com/barryvdh/laravel-cors in Laravel.


SPA domain: web.example.com API domain: example.com/test

I tested it by changing the API domain to the main domain.

I activated mod_header in Centos.


// my kernel with laravel package
protected $middlewareGroups = [
        'api' => [
            \Barryvdh\Cors\HandleCors::class,
        ],
    ];
// my kernel with cors middleware that i created manually
protected $middleware = [
        \App\Http\Middleware\Cors::class,
    ];
// my api route 
Route::namespace('Api')->middleware('cors')->group(function () {

Upvotes: 2

Views: 3990

Answers (1)

Devin Price
Devin Price

Reputation: 456

I have this working in one of my projects: https://github.com/devinsays/laravel-react-bootstrap/search?q=cors&unscoped_q=cors.

In app/Http/Kernel.php:

'cors' => \Barryvdh\Cors\HandleCors::class,

In the routes:

// Auth Endpoints
Route::group([
    'middleware' => 'cors',
    'prefix' => 'api'
], function ($router) {
    Route::post('example', 'Auth\ExampleController');
});

And in cors/config.php:


<?php
return [
    /*
    |--------------------------------------------------------------------------
    | Laravel CORS
    |--------------------------------------------------------------------------
    |
    | allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
    | to accept any value.
    |
    */
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedOriginsPatterns' => [],
    'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
];

Hopefully this helps!

Upvotes: 1

Related Questions