fruitcake / laravel-cors

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
MIT License
6.27k stars 615 forks source link

Error (No 'Access-Control-Allow-Origin' header is present on the requested resource.) #127

Closed vitalibr closed 7 years ago

vitalibr commented 8 years ago

Hi all and @barryvdh,

I created an application in AngularJS and I'm trying to make calls to the Laravel API:

I use Laravel API Boilerplate (JWT Edition) to API.

But I get this error in the browser console:

XMLHttpRequest cannot load http://localhost:8000/api/auth/login. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access.

I tried to apply the cors middleware (barryvdh/laravel-cors) in api_routes.php but the error remains.

api_routes.php:

<?php

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', ['middleware' => 'cors'], function ($api) {

    $api->post('auth/login', 'App\Api\V1\Controllers\AuthController@login');
    $api->post('auth/signup', 'App\Api\V1\Controllers\AuthController@signup');
    $api->post('auth/recovery', 'App\Api\V1\Controllers\AuthController@recovery');
    $api->post('auth/reset', 'App\Api\V1\Controllers\AuthController@reset');

    // example of protected route
    $api->get('protected', ['middleware' => ['api.auth'], function () {     
        return \App\User::all();
    }]);

    // example of free route
    $api->get('free', function() {
        return \App\User::all();
    });

});

My config/cors.php:

return [
    'supportsCredentials' => false,
    'allowedOrigins' => ['*'],
    'allowedHeaders' => ['*'],
    'allowedMethods' => ['*'],
    'exposedHeaders' => [],
    'maxAge' => 0,
    'hosts' => [],
];

Error: Error Error

gettosin4me commented 7 years ago

@ghprod use the code below, group the middleware with api

Route::group(['middleware' => ['api']], function () {
     Route::post('/users', [
         'uses' => 'Controller@method'
    ])
});

hope it works for u??

fer-ri commented 7 years ago

@gettosin4me nope, maybe its because i'm using together with Dingo API?

The only way to make it works only by using it as global middleware ..

gettosin4me commented 7 years ago
$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {
    $api->group(['middleware' => []], function ($api) {
        $api->group(['middleware' => ['user.api.key']], function ($api) {
            For endpoint that are secure
        });
            For unendpoint that are secure
    });
});
fer-ri commented 7 years ago

Thanks @gettosin4me for your respond, really appreciate :+1:

ux-engineer commented 7 years ago

Same here, @gettosin4me solution did not work. Am on 5.4.

allen-hxn commented 7 years ago

Same here.i am on laravel5.4 dingapi laravel-cors 0.9 php7.0 i add

 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,
        ],

        'api' => [
            'throttle:60,1',
            'bindings',
            \Barryvdh\Cors\HandleCors::class,
        ],
    ];

api.php

$api = app('Dingo\Api\Routing\Router');

$api->version('v1', function ($api) {

    $api->group(['namespace'=>'App\Http\Controllers\Api'], function ($api) {

        $api->post('login', 'Auth\LoginController@login');
......

cors middleware don't work. do you solve this issue? @vitalibr @envision

mycarrysun commented 7 years ago

@allen-hxn For some reason I think the order matters in the array. Try: 'api' => [ '\Barryvdh\Cors\HandleCors::class, 'throttle:60,1', 'bindings' ]

ghost commented 7 years ago

I'm facing the same issue atm in Laravel 5.4 using an Angular 2 frontend - you can find the whole story on stackoverflow: https://stackoverflow.com/questions/46991025/access-control-allow-origin-header-response-in-laravel-5-4-not-working-for-post

@mycarrysun Apparently it's the same for 5.4 - it has to be

    Route::prefix('api')
         ->middleware('api')
         ->middleware('cors')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));

instead of

    Route::prefix('api')
         ->middleware('cors')
         ->middleware('api')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));

order appears to matter ..

rwngallego commented 6 years ago

I had the same problem reported here and the solution was to change the order in the array that @mycarrysun mentioned. So I think the documentation should be updated to reflect this. Otherwise a lot of people will be shouting here for the same problem.

Originally, the doc says:

If you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:
protected $middlewareGroups = [
    'web' => [
       // ...
    ],

    'api' => [
        // ...
        \Barryvdh\Cors\HandleCors::class,
    ],
];

It should be:

    'api' => [
        \Barryvdh\Cors\HandleCors::class,
        // ...
    ],
sharadjaiswal1411 commented 6 years ago

Great tutorial on Handling cors in Laravel 5.5 http://www.laravelinterviewquestions.com/2017/12/cross-origin-request-blocked-error-laravel.html

AfzalH commented 6 years ago

I was having the same error while uploading larger images.

The error message on browser console was a bit misleading, it was showing No 'Access-Control-Allow-Origin' header is present with a status code 500. I was looking into the cors related things because of that error message but actually I had to look into the server error log (laravel.log was empty as well in my case).

After looking into nginx error log, I found out php was out of memory while processing the image using Intervention/Image

So if it's No 'Access-Control-Allow-Origin with 500 status code, take a look into your server's error log files (or laravel.log). Otherwise just putting the middleware in the correct position should work (as suggested by others)

salipro4ever commented 6 years ago

Can you try my solutions, they are working for me (laravel 5.5)

Solution 1. Init Cors middleware on global HTTP middleware in Kernel.php Solution 2. Still init api group middleware $middlewareGroups['api'], must add more options request in route routes/api.php. (for me)

Route::options('{any?}', function (){
    return response('',200);
})->where('any', '.*');

Guk luk!

jsims9817 commented 6 years ago

I was still getting a 500 error when trying to configure laravel-cors on Laravel 5.6. My solution... run composer require barryvdh/laravel-cors in /app/Kernel.php add \Barryvdh\Cors\HandleCors::class, to protected $middleware Run php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Don't do anything else... Adding it to the protected $middlewareGroups section was giving me 500 errors.

riteshjha commented 5 years ago

thanks @goeroeku saved my day

josepedrodiaz commented 5 years ago

I was having a similar issue, but the cause was not this module, the cause was api controller route was returning an error 500, after solved the issue on the controller (on my case a misconfiguration of database connection settings) CORS error disappear.