Skip to content
This repository has been archived by the owner on Feb 16, 2023. It is now read-only.

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

Closed
vitalibr opened this issue Aug 3, 2016 · 65 comments

Comments

@vitalibr
Copy link

vitalibr commented Aug 3, 2016

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

@victor-ponamariov
Copy link

Same here

@vitalibr
Copy link
Author

vitalibr commented Aug 3, 2016

@victor-ponamariov I've tried n ways and nothing solves this problem.
Can anyone help us?

@chasewoo
Copy link

chasewoo commented Aug 4, 2016

Same problem. @victor-ponamariov

@chasewoo
Copy link

chasewoo commented Aug 4, 2016

@victor-ponamariov My App working! Because PHP ini bug:

PHP Deprecated:  Automatically populating $HTTP_RAW_POST_DATA is deprecated and will be removed in a future version. To avoid this warning set 'always_populate_raw_post_data' to '-1' in php.ini and use the php://input stream instead. in Unknown on line 0

Change php.ini to reslove this problem. This is not laravel-cors bug.

@renielsalvador
Copy link

@vitalibr
We are also having the same issue. We are also using the angularjs and laravel. Hope to get some help for this. thanks.

@naderst
Copy link

naderst commented Aug 23, 2016

Don't use Wamp I fixed this issue using Xampp instead. Hope this help

@simplenotezy
Copy link

I managed to fix this issue.

I noticed my composer was using dev-master, and I am using Laravel 5.2. The most recent release adds support for laravel 5.3 so I figured this might be lacking backwards compatibility with 5.2.

Updating my composer.json to require 0.8.1 fixed the issue on Laravel v 5.2.*.

Solution:

Update composer.json to:

"barryvdh/laravel-cors": "0.8.1",

@eagle-r
Copy link

eagle-r commented Sep 6, 2016

I use Laravel 5.1 and tried updating to the latest version of laravel-cors but no luck for me. Anyone else have another suggestion?

@sandervanhooft
Copy link

Same here. I am able to GET/POST to normal routes though, but no luck with file upload (POST).

@kenny-lee-1992
Copy link

Same here, but this error only appear when i try to use ng-resource

@sandervanhooft
Copy link

sandervanhooft commented Sep 7, 2016

My issue was solved by moving all (instead the laravel api only) servers to
https. I don't know what was going on though, if this was the real issue
the error message seems unrelated.

EDIT: not really solved... :( See comment below.
On wo 7 sep. 2016 at 09:30, Jack Ho notifications@github.com wrote:

Same here, but this error only appear when i try to use ng-resource


You are receiving this because you commented.
Reply to this email directly, view it on GitHub
#127 (comment),
or mute the thread
https://github.com/notifications/unsubscribe-auth/AG7dp7ZBtvzO-NNFB-aWYMR-cztV-Lwzks5qnmgKgaJpZM4Jb-PO
.

@kenny-lee-1992
Copy link

Solved! I have checked my laravel log, and there are some error from back-end. Although, the front-end show error "No 'Access-Control-Allow-Origin'..."

Best Regards,

@sandervanhooft
Copy link

@barryvdh et al,

Ok, so I found out my issue was not really solved... Any clue on this one?

I've updated to 0.8.2 as this should include a fix for loading the middleware on route groups, but the issue persists if the controller should return an error (i.e. no status code 20*, but a 500 instead).

This use case regards a POST request using whatwg-fetch. The controller should invalidate the included file if it's not an image.

Symptoms:

  • In case of a correct file, the controller processes the image ok and returns a 201 response with some data. This works fine.
  • In case of a basic or cors request, the dreaded No 'Access-Control-Allow-Origin' header is present on the requested resource. is thrown in the browser console, suggesting I should try a no-cors request. I don't get a (500) response.
  • In case of a no-cors request, I get an opaque response which is unusable. I can see in the network logs it bears the error message, but there's (by design, as I understand) no way to retrieve it.

@goeroeku
Copy link

goeroeku commented Sep 9, 2016

I have same problem using laravel 5.2, php 5.6 on windows x64.
I try to disable always_populate_raw_post_data on php.ini (ref: http://php.net/manual/en/ini.core.php#ini.always-populate-raw-post-data), and Solved my problem ;)

@sandervanhooft
Copy link

@goeroeku Did you set it to -1? I am going to try this.

@sandervanhooft
Copy link

Did not solve the issue. I've tried adding this on top of public/index.php (deployed with Laravel Forge):

  • ini_set('always_populate_raw_post_data', 0);
  • ini_set('always_populate_raw_post_data', "0");
  • ini_set('always_populate_raw_post_data', -1);
  • ini_set('always_populate_raw_post_data', "-1");

Any clue?

@goeroeku
Copy link

goeroeku commented Sep 9, 2016

@sandervanhooft variable always_populate_raw_post_data can't set with ini_set, you must set it on php.ini
ref.

image

add phpinfo() on public/index.php to ensure the configuration is correct

@sandervanhooft
Copy link

@goeroeku Just tried it (thanks!), but it seems deprecated in the PHP version I use (PHP7.0). So it does not pop up in the phpinfo(). The issue persists.

What PHP version are you using? Any other thoughts?

@tabirkeland
Copy link

tabirkeland commented Sep 9, 2016

All,

Running Laravel Framework version Lumen (5.2.9) (Laravel Components 5.2.*) and PHP 5.5.9.

I initially installed v0.8.2 and then read @simplenotezy 's comment.

Downgraded to v0.8.1 and problem solved.

@barryvdh
Copy link
Member

barryvdh commented Sep 9, 2016

So 0.8.2 is broken, 0.8.1 works?

@tabirkeland
Copy link

@barryvdh I did not test 0.8.2 on Laravel/Lumen 5.3

@pnkz19
Copy link

pnkz19 commented Sep 22, 2016

Using with Laravel 5.3 + Laravel Passport and laravel-cors v0.8.2 on PHP 5.6.13

If try adding cors to any middleware group its seem preflight options doesn't added the Access-Control-Allow-Origin to the headers.

So, I've tried adding \Barryvdh\Cors\HandleCors::class to the global middleware and everything works fine.

@raphaelbadia
Copy link

raphaelbadia commented Oct 10, 2016

Using Laravel 5.3 + laravel-cors v0.8.2 on PHP 7.0.8

I get the error message:

XMLHttpRequest cannot load http://mmorts.dev/api/v1/login. Response to preflight request doesn't pass access control check: The 'Access-Control-Allow-Origin' header contains multiple values '*, http://client.dev', but only one is allowed. Origin 'http://client.dev' is therefore not allowed access.

It works on PHP 5.6, though. There is something wrong with PHP7, I can't find out what.

Edit:

...

Well, by removing laravel-cors entirely from my project and adding header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}"); in my index.php, I got CORS working but this isn't really the solution I wanted. It looks like that laravel-cors set this header twice (?).

@Sloaix
Copy link

Sloaix commented Oct 14, 2016

Same problem. Lumen5.3 + laravel-cors v0.8.2

@Sloaix
Copy link

Sloaix commented Oct 14, 2016

i solved it.my lumen api cause a error.but there is no any error show in response.

@andreluizmorita
Copy link

Same problem. :/

@mycarrysun
Copy link

Getting the same error, Laravel 5.3.26 Laravel-cors 0.8.2
Also tried v0.8.1 but got the same error.
Anyone make any progress on this yet?

@spopov
Copy link

spopov commented Dec 28, 2016

If someone override HandleCors class, you have to override Barryvdh\Cors\HandlePreflight also, because if you don't use HandleCors it skips OPTION request in HandlePreflight and returns nothing it why Access-Control-Allow-Origin is null

@ProgrammedMikey
Copy link

I get the same error, it works on localhost but not when i deploy it to production. Getting

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

@spopov
Copy link

spopov commented Jan 12, 2017

If you don't override HandleCors class, need to check any errors and also don't forget to add cors headers if exaction happens in an exception handler.

@barryvdh
Copy link
Member

Closing this as part of an issue-cleanup. Please re-open if this is still an issue on the latest version.

@varuntaliyan
Copy link

I am struggling with this error from last 2 days.
I am using Laravel 5 (backend) with "barryvdh/laravel-cors": "0.7.x" and angularjs 1.4 (frontend).
Error message exactly same as @vitalibr .
If anyone is able to resolve it, Please help

@varuntaliyan
Copy link

@Minhlong : Can you please share how you manage to resolve this ?

@barryvdh
Copy link
Member

Try the latest version

@varuntaliyan
Copy link

I tired installing the latest version but its not supported with laravel 5.1 and I cann't update the version of laravel

@barryvdh
Copy link
Member

Yes it is. Otherwise please create a seperate issue.

@jcduenasr
Copy link

Laravel v5.4.15, cors v0.9.2. php 5.6.25. It Doesn't Work...

@varuntaliyan
Copy link

I was using laravel 5.1, cors 0.7.x with angularjs 1.4 while getting this issue. But in the end it turns out that problem was due to completely different reasons.
So, my advice to everyone getting the issue is to check laravel logs. Do NOT trust the error msgs on client side, those error messages can be misleading.

@jcduenasr
Copy link

In the laravel logs there aren't error msgs. Laravel v5.4.15, cors v0.9.2. php 5.6.25. It Doesn't Work. : (

@barryvdh
Copy link
Member

Please create a new issue with you exact configuration and steps you followed. And make sure you registered the Service Provider AND the middleware.
Try to debug if the middleware is hit and if so, why it's not returning the correct code, for example by adding logger() statements.

@ikyandhi
Copy link

ikyandhi commented May 1, 2017

I try to debug HandleCors, notice those OPTIONS / Pre-flight request doesn't hit the middleware.

@Rajukumar468
Copy link

I had same problem with PHP 7 /laravel 5.4
i solved using @roman-klauser comments.

put into index.php
header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header('Access-Control-Allow-Headers: content-type');

@gettosin4me
Copy link

gettosin4me commented Aug 17, 2017

I had the same problem

but solved it by

set the cors in your api middleware like this

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

Hope this solved the problem

And also, make sure all your endpoint should be group with api middleware.

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

Hope it help someone

@fer-ri
Copy link

fer-ri commented Aug 24, 2017

@gettosin4me not working for me, gave me this error

ErrorException: Illegal offset type in isset or empty

/vendor/laravel/framework/src/Illuminate/Routing/Router.php:722

@gettosin4me
Copy link

@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
Copy link

fer-ri commented Aug 25, 2017

@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
Copy link

gettosin4me commented Aug 25, 2017

$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
Copy link

fer-ri commented Aug 25, 2017

Thanks @gettosin4me for your respond, really appreciate 👍

@ux-engineer
Copy link

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

@allen-hxn
Copy link

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
Copy link

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

@ghost
Copy link

ghost commented Oct 28, 2017

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
Copy link

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
Copy link

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

@AfzalH
Copy link

AfzalH commented Jan 31, 2018

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
Copy link

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
Copy link

jsims9817 commented Jul 6, 2018

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
Copy link

thanks @goeroeku saved my day

@josepedrodiaz
Copy link

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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests