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' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'cors' => \App\Http\Middleware\CORS::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!
This answer is based on this article. barryvdh/laravel-cors middleware library, can be used to fix the problem(Cross-Origin Resource Sharing).
step 1 Install it:
step 2 Releasing vendor files of the library:
step 3 The command ran in step 2 will copy a cors.php file to config directory, which looks like this:
For
allowedOrigins
the value can either be['*']
which indicated that the origin of request can be from any domain, or an array of specific domains which can be the origins that we will allow to send request to ourapi
, like this['first.com', 'second.com', 'register.third.com']
and also
allowedMethods
can either be['*']
or a list of allowedHTTP verbs
for instance['POST', 'GET']
step 4 Registering the cors middleware. Open
app/Http/kernel.php
and add theHandleCors
class to$routeMiddleware
like this:step 5 Now you can add the
laravel-cors
middleware to any route that you want. For instance inRoutes/api.php
I will do this:The issue arises from the preflight request, indeed, but the way of handling requires some additional explanation, when we're talking about Laravel - mainly
OPTIONS
request is routed (something the other answers rather do PHP way, than Laravel way), so, you have to add this to your routes for it to be successfull:Route::options('/{any}', function(){ return ''; })->where('any', '.*');
Now, let's cater for all other methods - create CORS middleware:
And finally, for given route, use that middleware:
Route::put('/test', function(){ echo('test'); })->with('cors');
You can bypass this one without using any middleware like Barryvdh\Cors for Laravel which was not working properly with JWT AUTH , I have added the following statements in the index.php in Laravel just before the Kernel instantiation
add this one before
this should work properly with JWT AUTH also. Kindly note that in Access-Control-Allow-Headers you should include Authorization otherwise your accesstoken will not be allowed with Authorization header therefore JWT AUTH will fail. Happy Coding.
Clearly not the ideal solution but it WORKS. I've added this to the top of my routes.php file:
It would be nice to get this working without a hack... alas.
UPDATE: It turned out to be IIS related. I ended up setting the headers in the web.config file and now CORS works without hacking the routes.php file.
If you want to restrict access, you can add outbound rules:
I solve my problem just adding these line on my routes.php Laravel 5.2 For greater then 5.2 in routes/web.php
OR register Cors middleware in global HTTP middleware stack
Your middleware is ok but you need to register Cors middleware in global HTTP middleware stack.