Laravel Production, CORS No 'Access-Control-Allow-Origin' header

Viewed 2345

After deploying my Laravel API app on Heroku it seems to be having issues with Cors. This was no issue in development, and I can still use the deployed app on postman, but not through regular HTTP requests on my Angular app.

enter image description here

My Cors.php is the has not been modified

   'paths' => ['api/*', 'sanctum/csrf-cookie'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => ['*'],

    'allowed_headers' => ['*'],

    'exposed_headers' => [],

    'max_age' => 0,

    'supports_credentials' => true,

And my Kernel.php uses the HandleCors class

 protected $middleware = [
        // \App\Http\Middleware\TrustHosts::class,
        \Fruitcake\Cors\HandleCors::class,
        \App\Http\Middleware\TrustProxies::class,
        \App\Http\Middleware\PreventRequestsDuringMaintenance::class,
        \Illuminate\Foundation\Http\Middleware\ValidatePostSize::class,
        \App\Http\Middleware\TrimStrings::class,
        \Illuminate\Foundation\Http\Middleware\ConvertEmptyStringsToNull::class,
    ];

Not sure if my angular app needs further changes, since it's working on postman, the call looks like this

  // User registration
  register(user: User): Observable<any> {
    return this.http.post('https://secure-fortress-48055.herokuapp.com/api/register', user);
  }

Any ideas on how to solve this?

2 Answers

Can you post your .env file? I think you need to modify your .env file and change the following code

APP_URL=http://localhost

to

APP_URL=https://secure-fortress-48055.herokuapp.com/

also you need to change Cors.php

    'exposed_headers' => [],

to

    'exposed_headers' => ['Access-Control-Allow-Origin'],

Maybe this will help you

I solved it by adding headers inside of the api.php routes

header('Access-Control-Allow-Origin:  *');
header('Access-Control-Allow-Methods:  POST, GET, OPTIONS, PUT, PATCH, DELETE');
header('Access-Control-Allow-Headers: Accept, Content-Type, X-Auth-Token, Origin, Authorization');

Maybe not the most elegant solution, but it's one.

Related