Saturday, November 16, 2024
Google search engine
HomeLanguagesLaravel cors – no ‘access-control-allow-origin’ header is present on the requested resource

Laravel cors – no ‘access-control-allow-origin’ header is present on the requested resource

Laravel cors – no ‘access-control-allow-origin’ header is present on the requested resource; In this tutorial, you will learn how to enable CORS (Cross-Origin Resource Sharing) in Laravel 10/9/8/7 to fix/resolve no ‘access-control-allow-origin’ header is present on the requested resource laravel.

Laravel CORS: How to Enable CORS in Laravel

If you found access-control-allow-origin htaccess Laravel 10/9/8/7 issue, you can use the following ways to resolve/fix no ‘access-control-allow-origin’ header is present on the requested resource in laravel 10/9/8/7:

  1. Laravel CORS
  2. CORS Middleware Nitty-Gritty
  3. Create API in Laravel
  4. Make Http GET Request using AJAX
  5. Occur Laravel CORS Error Access-Control-Allow-Origin
  6. Install CORS Library in Laravel
  7. Registering CORS Middleware

Laravel CORS

First of all, execute the following command on terminal to install a fresh Laravel app;

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

Then execute following 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, Visit 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 using AJAX

Let’s create one blade view file, which name demo.html and add the following code into it to make http get request using ajax;

<!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</title>
</head>
<body>
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/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>

Occur Laravel CORS Error Access-Control-Allow-Origin

If you found this error laravel cors (No ‘Access-Control-Allow-Origin’ header is present on the requested resource.), it occurred because you have two different domain trying to exchange data with each other. And yes you haven’t even enabled the CORS yet.

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

Install CORS Library in Laravel

Execute the following command on terminal to Install fruitcake/laravel-cors package to resolve cors issue;

composer require fruitcake/laravel-cors

Registering CORS Middleware

Then configure CORS (Cross-Origin Resource Sharing) headers support in your Laravel application.

So, open routes in app/Http/Kernel.php file. and  \Fruitcake\Cors\HandleCors class at the top inside $middleware array to enable CORS;

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

Conclusion

That’s it; In this tutorial, you have learned how to enable CORS (Cross-Origin Resource Sharing) in Laravel 10/9/8/7 to fix/resolve no ‘access-control-allow-origin’ header is present on the requested resource laravel.

Recommended Laravel Tutorials

RELATED ARTICLES

Most Popular

Recent Comments