The dreaded CORS Error:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading
the remote resource at http://localhost/mysite/api/test. (Reason: CORS
header 'Access-Control-Allow-Origin' missing).
Laravel route:
$router->group(['prefix' => 'api', 'middleware' => 'cors'], function ($router) {
$router->get('/test', 'MyController@myMethod');
});
Laravel Cors Middlware:
public function handle($request, Closure $next)
{
header('Access-Control-Allow-Origin: *');
// ALLOW OPTIONS METHOD
$headers = [
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => 'Content-Type, X-Auth-Token, Origin, Authorization'
];
if ($request->getMethod() == "OPTIONS") {
// The client-side application can set only headers allowed in Access-Control-Allow-Headers
return Response::make('OK', 200, $headers);
}
$response = $next($request);
foreach ($headers as $key => $value)
$response->header($key, $value);
return $response;
}
Laravel Kernel:
protected $routeMiddleware = [
'auth' => AppHttpMiddlewareAuthenticate::class,
'auth.basic' => IlluminateAuthMiddlewareAuthenticateWithBasicAuth::class,
'guest' => AppHttpMiddlewareRedirectIfAuthenticated::class,
'throttle' => IlluminateRoutingMiddlewareThrottleRequests::class,
'cors' => AppHttpMiddlewareCORS::class
];
Relevant .htaccess:
RewriteCond %{HTTP:Authorization} .
RewriteRule .* - [E=HTTP_AUTHORIZATION:%{HTTP:Authorization}]
Relevant Vue.js:
new Vue({
el: '#app',
data: {
//data here
},
http: {
headers: {
"Authorization": "Basic " + "apiKeyHere"
}
},
methods: {
mymethod: function (e)
{
e.preventDefault();
this.$http.get('http://localhost/mysite/api/test').then(
function (response)
{
//do something
}
)
}
}
});
If I take out the Authorization header option the request works.
I've also tried https://github.com/barryvdh/laravel-cors but still no joy.
Any help appreciated!
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…