skip to Main Content

Getting below error while calling API from Angular to Laravel

Access to XMLHttpRequest at ‘http://localhost:8000/api/v1/authenticate’ from origin ‘http://localhost:4201’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

I already tried adding headers in Angular for CORS but nothing worked for me.
I have checked Laravel 10 cors file every thing is good from there and I also added below code in boostrap/app.php

header("Access-Control-Allow-Headers: Origin, userKey, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Access-Control-Allow-Headers, Authorization, observe, enctype, Content-Length, X-Csrf-Token");
header("Access-Control-Allow-Methods: GET, POST");
header("Access-Control-Allow-Credentials: true");
header("Access-Control-Max-Age: 3600");
header('content-type: application/json; charset=utf-8');

2

Answers


  1. Laravel has a popular package called fruitcake/laravel-cors that you can use to handle CORS.

    composer require fruitcake/laravel-cors
    
    php artisan vendor:publish --tag="cors"
    

    config/cors.php:

    'allowed_origins' => ['http://localhost:4201'], // or maybe ['*']
    

    Ensure the Cors middleware is included in your global middleware or in your API middleware group in app/Http/Kernel.php:

    FruitcakeCorsHandleCors::class,
    

    Don’t forget to run:

    php artisan config:clear
    
    Login or Signup to reply.
  2. Try below Suggestion, Add Middle as instructed in Stack Overflow Answer.

    CORS error, unable to solve, Why always getting Access-Control-Allow-Origin?

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search