I have successfully set cors
middleware with Laravel as describer here
Therefore, this ajax call is ok
axios.get('http://my_domain/api/my_api')
But when trying to send token like this:
axios.get('http://my_domain/api/my_api',
{
headers: {
Authorization: 'Bearer aaa.bbb.ccc'
}
})
I get a cors erros saying Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
I have even added Access-Control-Allow-Headers
in the middleware, I still have the issue.
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Log;
class Cors {
public function handle($request, Closure $next) {
Log::info("Using cors for ".$request->url());
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Authorization');
}
}
Can anyone help please?
I earnestly tried to find solution on this, and here is what resolved mine. I had to add 03 edits simultaneously:
1) Add the cors in route middleware
protected $routeMiddleware = [
...
'cors' => \App\Http\Middleware\Cors::class,
];
2) Add the cors in global middlewre
protected $middleware = [
...
\App\Http\Middleware\Cors::class,
];
3) Add custom Access-Control-Allow-Headers
in Cors middleware app/Http/Middleware/Cors.php
<?php namespace App\Http\Middleware;
use Closure;
use Illuminate\Http\Request;
use Log;
class Cors {
public function handle($request, Closure $next) {
Log::info("Using cors for " . $request->url());
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With');// <-- Adding this
}
}
If someone can explain why it worked, that would be great to understand its behavior.