fruitcake / laravel-cors

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
MIT License
6.27k stars 613 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

victor-ponamariov commented 8 years ago

Same here

vitalibr commented 8 years ago

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

chasewoo commented 8 years ago

Same problem. @victor-ponamariov

chasewoo commented 8 years ago

@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 commented 8 years ago

@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 commented 8 years ago

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

simplenotezy commented 8 years ago

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 commented 8 years ago

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 commented 8 years ago

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

kenny-lee-1992 commented 8 years ago

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

sandervanhooft commented 8 years ago

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 https://github.com/barryvdh/laravel-cors/issues/127#issuecomment-245198551, or mute the thread https://github.com/notifications/unsubscribe-auth/AG7dp7ZBtvzO-NNFB-aWYMR-cztV-Lwzks5qnmgKgaJpZM4Jb-PO .

kenny-lee-1992 commented 8 years ago

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 commented 8 years ago

@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:

goeroeku commented 8 years ago

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 commented 8 years ago

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

sandervanhooft commented 8 years ago

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

Any clue?

goeroeku commented 8 years ago

@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 commented 8 years ago

@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 commented 8 years ago

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 commented 8 years ago

So 0.8.2 is broken, 0.8.1 works?

tabirkeland commented 8 years ago

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

pnkz19 commented 8 years ago

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 commented 8 years ago

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 commented 8 years ago

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

Sloaix commented 8 years ago

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

andreluizmorita commented 8 years ago

Same problem. :/

mycarrysun commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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.

ProgrammedMikey commented 7 years ago

yea its fixed, i just switched server to nginx on heroku, thanks working great

alexvlrt commented 7 years ago

I got this problem, and I tried everything that you said execpts overriding HandleCors (Dunno how to do it) and it doesn't works. Anybody have a concrete solution ?

roman-klauser commented 7 years ago

Not the best solution, especially NOT for production, but after few days of searching just happy that it works and I can move on.

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

PHP 7.0/Laravel 5.4

cheanizer commented 7 years ago

@sandervanhooft are your issue really solve. same here. if the response status are 2xx everything worked. but when it become 500,422 (laravel boilerplate send 422 for validation error). got cors error. I need catch the 422 data message when validation rejected from api. but now, it show null and when I see in the network tab (from inspect element), it show the message. using angular 1.5.9, laravel 5.2, cors 0.7.1. php 7

sandervanhooft commented 7 years ago

I don't know, I found the issue too confusing and moved to another stack On Sun, 19 Feb 2017 at 14:56, Adhi Setyawan notifications@github.com wrote:

@sandervanhooft https://github.com/sandervanhooft are your issue really solve. same here. if the response status are 2xx everything worked. but when it become 500,422 (laravel boilerplate send 422 for validation error). got cors error. I need catch the 422 data message when validation rejected from api. but now, it show null and when I see in the network tab (from inspect element), it show the message. using angular 1.5.9, laravel 5.2, cors 0.7.1. php 7

— You are receiving this because you were mentioned. Reply to this email directly, view it on GitHub https://github.com/barryvdh/laravel-cors/issues/127#issuecomment-280920707, or mute the thread https://github.com/notifications/unsubscribe-auth/AG7dpxm1lInVAJQzHxfZBQfDgcN-ydhmks5reEoRgaJpZM4Jb-PO .

axis80 commented 7 years ago

I was able to get this working under PHP 7. In the end, my main problem was that the CSRF middleware was blocking the incoming requests since there was no CSRF token included with them. I had to edit App/Http/Middleware/VerifyCsrfToken.php and add my URI endpoint to the list of routes that are excepted from CSRF verification.

barryvdh commented 7 years ago

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

varuntaliyan commented 7 years ago

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 commented 7 years ago

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

barryvdh commented 7 years ago

Try the latest version

varuntaliyan commented 7 years ago

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

barryvdh commented 7 years ago

Yes it is. Otherwise please create a seperate issue.

jcduenasr commented 7 years ago

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

varuntaliyan commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

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

Rajukumar468 commented 7 years ago

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 commented 7 years ago

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 commented 7 years ago

@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