No Access-Control-Allow-Origin header is present on the requested resource Angular Laravel

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.