0

full error message :

Access to XMLHttpRequest at 'https://api_url' from origin 'http://localhost:3000' has been blocked by CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response.

I cannot fixed this cors problem .

my vue component code :

test(){
  axios.get("https://api_url")
  .then(response => {
        this.data = response.data.data;
  });
}

I also create a middleware & add it to protected array $middleware in Kernel.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)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Credentials', 'true')
            ->header('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS, POST, PUT')
            ->header('Access-Control-Max-Age', '3600')
            ->header('Access-Control-Allow-Headers', 'Origin, Accept, Content-Type, X-Requested-With');
    }
}
theduck
  • 2,589
  • 13
  • 17
  • 23

2 Answers2

0

Use this package and it will solve your problem https://github.com/barryvdh/laravel-cors

Mohammed Aktaa
  • 1,345
  • 9
  • 14
0

Use this package like @Mohammed Aktaa suggested: https://github.com/barryvdh/laravel-cors

Add the HandleCors middleware to your api $middlewareGroup array in app/Http/Kernel.php:

'api' => [
    // ...
    \Barryvdh\Cors\HandleCors::class,
],

Publish the configuration of the package:

$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"

Edit the configuration to use the CORS_ORIGIN environment variable for the allowed origin:

'allowedOrigins' => [env('CORS_ORIGIN', '')],

In your .env file, add an entry for your local origin:

CORS_ORIGIN="http://localhost:3000"
brice
  • 1,801
  • 1
  • 10
  • 15