Reputation: 1187
XMLHttpRequest cannot load http://myapi/api/rating. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8104' is therefore not allowed access. The response had HTTP status code 403.
I can't figure out why I can't make CORS requests. I've install the middleware here, added it to the global http kernel, but it still doesn't work. Tried to create a custom middleware given stackoverflow suggestions but that also did not work. Also tried adding a Route group. Lastly, I tried setting the response headers manually in the request action. I'm really stuck - help is appreciated!
See for code: https://gist.github.com/KerryRitter/0d7ababb7b9eb8d54f0ae55add9704a1
Upvotes: 29
Views: 131744
Reputation: 2566
I was using Sanctum Single Page Authentication, and I had defined all domains as mentioned in the documentation. The issue was that in the config/cors.php/allowed_origins value, I had indicated my Frontend host without the protocol scheme e.g. localhost.site instead of http://localhost.site. Remember the CORS documentation states that if you are not using wildcards in the origin, then you must put the scheme.
Note: For allowed_origins you must include the scheme when not using a wildcard, eg. ['http://example.com', 'https://example.com']. You must also take into account that the scheme will be present when using allowed_origins_patterns.
https://github.com/fruitcake/laravel-cors
Once i fixed that I was good.
Upvotes: 0
Reputation: 106
I had the error because some traits were missing in my models
use Laravel\Passport\HasApiTokens;
use Illuminate\Notifications\Notifiable;
So i added the header in the specific route, fixed theses errors, and then my headers went back to normal
header('Access-Control-Allow-Origin: *');
Upvotes: 0
Reputation: 26
In my case I had ran updates to move Laravel from v7.x to v9.x and resulted in localhost API access CORS errors.
If none of the above is working for you i tracked my issue down to the $headers variable within the TrustProxies Middleware.
The original value for this variable was Request::HEADER_X_FORWARDED_ALL;
After updating this to the below, it came back to life.
Request::HEADER_X_FORWARDED_FOR | Request::HEADER_X_FORWARDED_HOST | Request::HEADER_X_FORWARDED_PORT | Request::HEADER_X_FORWARDED_PROTO | Request::HEADER_X_FORWARDED_AWS_ELB;
See https://laravel.com/docs/9.x/upgrade and the Trusted Proxies section for reference.
What this all means for me is, read the whole of the upgrade docs, even if you dont think elements apply to your project...
Upvotes: 1
Reputation: 512
Just something I wanted to add something which I had to do in addition to the steps mentioned in the accepted answer.
I did encounter CORS error after couple of production deployments (Laravel version ^7.0 on Nginx) even after having setup HandleCors as mentioned here.
It started working after I ran php artisan config:cache
, composer install
and composer dump-autoload
.
Hope this helps someone who is trying to debug what went wrong when you haven't updated any config files during deployment.
Upvotes: 0
Reputation: 680
The simple answer is to set the Access-Control-Allow-Origin header to localhost or *. Here's how I usually do it:
Create a simple middleware called Cors
:
php artisan make:middleware Cors
Add the following code to app/Http/Middleware/Cors.php
:
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
You can replace the * with localhost
or keep it as it is.
Next step is to load the middleware
. Add the following line to the $routeMiddleware
array in app/Http/Kernel.php
.
'cors' => \App\Http\Middleware\Cors::class,
And the final step is to use the middleware on the routes to which you want to set the access origin headers. Assuming you are talking about the new api routes in laravel 5.3, the place to do it is app/Providers/RouteServiceProvider.php
, inside the mapApiRoutes()
function (you can remove or comment the previous code of the function):
Route::group([
'middleware' => ['api', 'cors'],
'namespace' => $this->namespace,
'prefix' => 'api',
], function ($router) {
//Add you routes here, for example:
Route::apiResource('/posts','PostController');
});
Upvotes: 4
Reputation: 1177
I worked on a composite project frontend Reactjs and Laravel backend when I encountered the "preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin". I resolved the problem by clearing the cache of the deployed Reactjs app on Heroku.
How do I clear the build cache?
Upvotes: 0
Reputation: 1139
If you are using Laravel 5.5
& Laravel 5.x
and facing same problem like No 'Access-Control-Allow-Origin' header is present on the requested resource
. Just use following package and config your system.
Step 1:
composer require barryvdh/laravel-cors
Step 2
You also need to add Cors\ServiceProvider
to your config/app.php
providers array:
FruitCake\Cors\CorsServiceProvider::class,
To allow CORS
for all your routes, add the HandleCors
middleware in the $middleware
property of app/Http/Kernel.php
class:
For global uses:
protected $middleware = [
// ...
\Fruitcake\Cors\HandleCors::class,
];
For middleware uses:
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
// ...
\Fruitcake\Cors\HandleCors::class,
],
];
Step 3
Once your installation completed run below command to publish the vendor files.
php artisan vendor:publish --provider="Fruitcake\Cors\ServiceProvider"
Hope this answer helps someone facing the same problem as myself.
Upvotes: 36
Reputation: 21
ok, here is my try. if i'm post to protected api using wrong token, passport return 401 with {"message":"Unauthenticated."}
but because there is no cors header exist on response, my vue app get CORS error and cannot handle the response code.
so at laravel 5.8 on http/kernel.php $middlewarePriority add \Barryvdh\Cors\HandleCors::class before \App\Http\Middleware\Authenticate::class
here is my code:
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:300,1',
'Localization',
'bindings',
'cors'
],
];
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
// Add Localization MiddleWare
'Localization' => \App\Http\Middleware\localization::class,
'cors' => \Barryvdh\Cors\HandleCors::class,
];
protected $middlewarePriority = [
\Illuminate\Session\Middleware\StartSession::class,
\Illuminate\View\Middleware\ShareErrorsFromSession::class,
//add to handle cors before authenticate
\Barryvdh\Cors\HandleCors::class,
\App\Http\Middleware\Authenticate::class,
\Illuminate\Session\Middleware\AuthenticateSession::class,
\Illuminate\Routing\Middleware\SubstituteBindings::class,
\Illuminate\Auth\Middleware\Authorize::class,
];
hope this help someone else
Upvotes: 2
Reputation: 467
Laravel restricts the cross origin request due to security issues by default. We need to create a Cors middleware to the accept the request from different origin.
Step 1 : Create Cors middleware.
php artisan make:middleware Cors
Step 2 : Add below lines in handle function before return.
//header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Origin: http://localhost:4200');
header('Access-Control-Allow-Headers: Content-Type, X-Auth-Token, Authorization, Origin');
header('Access-Control-Allow-Methods: POST, PUT');
Step 3 : Register the middileware in app/Http/Kernel.php file.
Add below line in $middleware array
\App\Http\Middleware\Cors::class,
Step 4 : Now we have to call the middleware in app/Http/Kernel.php file
Add below line in $routeMiddleware array
'cors' => \App\Http\Middleware\Cors::class,
Upvotes: 25
Reputation: 81
https://github.com/barryvdh/laravel-cors
The laravel-cors package allows you to send Cross-Origin Resource Sharing headers with Laravel middleware configuration.
Features
Handles CORS pre-flight OPTIONS requests Adds CORS headers to your responses
Upvotes: 5
Reputation: 882
I faced this error in laravel 5.4 recently, i was sending ajax post request to my own website, and was still getting this same error, i faced this error due to two reasons to be precise,
error: XMLHttpRequest cannot load https://[mydomain].com/quote/short. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://[mydomain].com' is therefore not allowed access.
The reason for above error was that, i was posting request to http domain from https domain, so when i changed it to https, the error was resolved, then again i got the same error due to similar reason, which was the reason, this time, the domain had www.
and the requested one did not, after i added www.
to both, it worked like a charm.
And for cross origin requests, i used to following solution:
Create a middleware (cors in my case) having code below
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
Insert middle-ware into routeMiddleware array in kernal.php
'cors' => \App\Http\Middleware\Cors::class,
Add middleware to the respected route
Route::get('myRoute', ['middleware' => 'cors' , 'uses'=> 'MyController@Action']
Hope this answer helps someone facing the same problem as myself.
Upvotes: 3