I have a laravel application with Vue running on the front end. The application is running on the localhost:8000, on the Vue side, I am trying to fetch data from another API e.g https://someapi.com/. However, I am getting this error, Access to XMLHttpRequest at 'https://someapi.com/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Research about the error brought me to this solution, this, and this as well as others but none works for me.
I created middleware:
<?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)
{
header("Access-Control-Allow-Origin: *");
$headers = [
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'
];
if ($request->getMethod() == "OPTIONS") {
return response()->make('OK', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value) {
$response->header($key, $value);
}
return $response;
}
}
then added it to routemiddleware array in Kernel.php:
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'cors' => \App\Http\Middleware\CORS::class,
];
then protected welcome route with it:
Route::middleware(['auth','cors'])->group(function () {
Route::get('/', function () {
return view('welcome');
});
});