No access-control-allow-origin header is present on the requested resource. laravel 8

No ‘Access-Control-Allow-Origin’ header – Laravel

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

Answer

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 CorsServiceProvider to your config/app.php providers array:

FruitCakeCorsCorsServiceProvider::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 = [ // ... FruitcakeCorsHandleCors::class, ];

For middleware uses:

protected $middlewareGroups = [ 'web' => [ // ... ], 'api' => [ // ... FruitcakeCorsHandleCors::class, ], ];

Step 3

Once your installation completed run below command to publish the vendor files.

php artisan vendor:publish --provider="FruitcakeCorsServiceProvider"

Hope this answer helps someone facing the same problem as myself.

I was woking on a Laravel API application for Angular. When I was working locally everything was working fine. But when i deploy the Laravel and Angular applications to the live server, I was getting CORS errors in Angular in browser console.

Access to XMLHttpRequest at 'https://laravel-api.com/api/call' from origin 'https://angular-app.com' 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.

This issue can be solved by adding appropriate headers in Laravel application. You can set this by adding Middleware in these routes. Here is the middleware file at /app/Http/Middleware/CORS.php

<?php namespace App\Http\Middleware; use Closure; class CORS {     /**      * Handle an incoming request.      *      * @param  \Illuminate\Http\Request  $request      * @param  \Closure  $next      * @return mixed      */     public function handle($request, Closure $next)     {                 $response = $next($request)             ->header('Access-Control-Allow-Origin', '*')             ->header('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE')             ->header('Access-Control-Allow-Headers', 'Origin, Content-Type, X-Auth-Token');     } }

Add the middleware to $routeMiddleware variable in app/Http/Kernel.php file.

protected $routeMiddleware = [    ....    'CORS' => \App\Http\Middleware\CORS::class,    .... ];

And add the middleware to route.

Route::get('/users/get-data','[email protected]')->middleware('CORS');

This should work and solve the issue.

Home  »  Laravel   »   Laravel 9 CORS Example: How to Enable CORS in Laravel?

Aren’t you able to share the resources between two servers or domains? Well, if you are going gaga over this enigma, then we have a solution for you.

In this tutorial, i will teach you how to easily enable CORS (Cross-Origin Resource Sharing) in Laravel and work with it. You can install CORS and configure it to get rid of CORS header ‘access-control-allow-origin’ missing problem.

Well, generally this problem occurs when the request is made from another server or origin because of security concern consensus doesn’t established between two servers. In response, we usually get No ‘Access-Control-Allow-Origin’ header is present on the requested resource.” warning. CORS authenticate the coherence between two different domains.

Read more: Laravel JWT Token-Based Authentication with Angular

Cross-origin resource sharing (CORS) is a mechanism that allows restricted resources on a web page to be requested from another domain outside the domain from which the first resource was served.
wikipedia

How to enable CORS in your REST API backend? First, we have to install a fresh Laravel app.

composer create-project laravel/laravel laravel-cors-tutorial --prefer-dist

Enter into the project folder:

cd laravel-cors-tutorial

If you have already installed the app then skip it and run the command to start the test the CORS in laravel app.

php artisan serve

CORS Middleware Nitty-Gritty

Along with new app installation, config/cors.php file also generated. Laravel allows following cors related configurations.

  • CORS configuration paths
  • Allowed methods
  • Allowed origins patterns
  • Allowed headers
  • Exposed headers
  • Max age
  • Supports credentials
<?php return [ /* |-------------------------------------------------------------------------- | Cross-Origin Resource Sharing (CORS) Configuration |-------------------------------------------------------------------------- | | Here you may configure your settings for cross-origin resource sharing | or "CORS". This determines what cross-origin operations may execute | in web browsers. You are free to adjust these settings as needed. | | To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS | */ 'paths' => ['api/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];

Create API in Laravel

To enable CORS in API, we need to have one, go to routes/api.php and incorporate the given below code.

<?php use Illuminate\Http\Request; use Illuminate\Support\Facades\Route; /* |-------------------------------------------------------------------------- | API Routes |-------------------------------------------------------------------------- | | Here is where you can register API routes for your application. These | routes are loaded by the RouteServiceProvider within a group which | is assigned the "api" middleware group. Enjoy building your API! | */ Route::get('/demo-url', function (Request $request) { return response()->json(['Laravel CORS Demo']); });

Make Http GET Request with AJAX

We will send the Http GET request using AJAX. To, manifest a new HTML template, name it demo.html. Call jQuery CDN link and define the AJAX function and pass the Laravel API to get the response.

<!doctype html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <!-- Bootstrap CSS --> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css" integrity="sha384-JcKb8q3iqJ61gNV9KGb8thSsNjpSL0n8PARn9HuZOnIxN0hoP+VmmDGMN5t9UJ0Z" crossorigin="anonymous"> <title>Laravel CORS Middleware Demo</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm//dist/jquery.min.js"></script> <script> $.ajax({ type: "GET", dataType: "json", url: 'http://localhost:8000/demo-url', success: function (data) { console.log(data); } }); </script> </body> </html>

Malevolent Laravel CORS Error

As we can see a CORS related error (No ‘Access-Control-Allow-Origin’ header is present on the requested resource.), it occurred because we have two different domain trying to exchange data with each other. And yes we haven’t even enabled the CORS yet.

Access to XMLHttpRequest at 'http://localhost:8000/demo-url' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Installing CORS Package in Laravel

As we have known what the ailment is, and now turn to cure this. With the help of Composer just Install fruitcake/laravel-cors package.

composer require fruitcake/laravel-cors

Registering CORS Middleware

We have added the quintessential CORS (Cross-Origin Resource Sharing) headers support in your Laravel application. Now, we have to configure it in our application.

Lastly, include \Fruitcake\Cors\HandleCors class at the top inside $middleware array to enable CORS for all our routes in app/Http/Kernel.php file.

protected $middleware = [ \Fruitcake\Cors\HandleCors::class, // ... // ... ];

We have implemented the CORS in Laravel to deal with resource sharing for different domains.