Laravel API CORS mode not working - laravel

I did a lot of research and I implemented the following middleware to get around the CORS error I keep getting...
Middleware/Cors.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-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS')
->header('Access-Control-Allow-Headers', 'content-type');
}
}
?>
Kernel.php
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'cors' => App\Http\Middleware\Cors,
];
Routes.php
Route::post('/content', array('middleware' => 'cors', 'uses' => 'Test#save'));
This seems to be configured properly. But when I make the request using fetch API...
fetch('http://laravel.dev/content', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Access-Control-Allow-Origin':'*'
},
body: JSON.stringify({
})
})
//.then((response) => response.json())
.then((response) => response.text())
.then((text) => {
console.log(text);
});
I still get this error...
Fetch API cannot load http://laravel.dev/content.
Response to preflight request doesn't pass access
control check: No 'Access-Control-Allow-Origin' header
is present on the requested resource.
I tried adding no-cors mode to my fetch response, and it worked, I got an opaque response, but I need cors mode to get a proper request.
It might be worthwhile to note that my App and my Laravel restAPI are located in the same htdocs folder on XAMPP. I'm not sure if this is an issue.
I also tried adding the headers at the top of my Routers.php file but I still get the same error. Can I even configure a restAPI using laravel?

Try to remove
->header('Access-Control-Allow-Headers', 'content-type');
in class Cors like this
<?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-Methods', 'GET,POST,PUT,PATCH,DELETE,OPTIONS');
}
}
?>
It worked for me.I hope it helpfull for you

Related

Enable CROS in Lumen 9.1.2

please can you explain me how can i enable CROS in Lumen step by step, am new in lumen and i done my api, but am trying consum from remote host and CRON is blocked, plis help.
error:
Access to fetch at 'http://api.alopez.es/users/login' from origin 'http://web.alopez.es:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.
Thanks in advance.
as this Documents
make new middleware CorsMiddleware
<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => '*',
'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Credentials' => 'true',
'Access-Control-Max-Age' => '86400',
'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With'
];
if ($request->isMethod('OPTIONS'))
{
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
$response = $next($request);
foreach($headers as $key => $value)
{
$response->header($key, $value);
}
return $response;
}
}
and Register your new middleware
Head over to your bootstrap/app.php file and register your new middleware with the following lines:
$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);

Laravel VerifyCsrfToken exclude not working

I'm having an issue excluding /api route from verifying token.
I'm trying to exclude all routes but not working
use Illuminate\Foundation\Http\Middleware\VerifyCsrfToken as Middleware;
class VerifyCsrfToken extends Middleware
{
/**
* The URIs that should be excluded from CSRF verification.
*
* #var array
*/
protected $except = [
//
'*',
];
}
What I suggest is, create a middleware and use it in your routes:
Create app/Http/Middleware/Cors.php
<?php
namespace App\Http\Middleware;
use Illuminate\Http\Request;
class Cors
{
/**
* Handle an incoming request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
* #return mixed
*/
public function handle(Request $request, \Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization');
return $response;
}
}
Modify app/Http/Kernel.php
protected $routeMiddleware = [
...
'cors' => \App\Http\Middleware\Cors::class,
];
Finally, use it in your route file eg: routes/web.php
Route::middleware(['cors'])->group(function () {
Route::get('/', 'YourController#yourFunction');
});

CORS policy: Request header field x-requested-with is not allowed by Access-Control-Allow-Headers in preflight response

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');
}
}
Use this package and it will solve your problem
https://github.com/barryvdh/laravel-cors
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"

How to use middleware and controller on one route

I have to add CORS policy to my request.
So I created middleware
I already tried the following :
Route::get('/test', ['middleware' => 'cors', 'cvGenerator#show'])
or
Route::get('/test', 'cvGenerator#show');
//inside controller
$this->middleware('cors');
but none of the above work. CORS policy still aborted
my middleware code:
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-Methods' , 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers' , 'X-Requested-With, Content-Type, Origin, Cache-Control, Pragma, Authorization, Accept, Accept-Encoding');
}
}
And Controller:
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use PDF;
use Illuminate\Support\Facades\Storage;
class cvGenerator extends Controller
{
public function show(Request $request)
{
$this->middleware('cors');
echo 'test';
//some code that generate output
}
}
How can I pass the request?
If you have just one route that should go through the middleware. Also middleware doesn’t belong in the controller.
Route::get('/test', 'cvGenerator#show')->middleware('cors');
If you have more than one route, you can use a route group.
Route::group(['middleware' => ['cors']], function () {
Route::get('/test', 'cvGenerator#show');
});
Also Laravel has a pretty good docs about middleware.
CORS
We're using this middleware to support pre-flight CORS requests:
<?php
namespace App\Http\Middleware;
use Closure;
class AddCorsHeaders
{
/**
* Check for CORS request.
*
* #param \Illuminate\Http\Request $request
* #param \Closure $next
*
* #return mixed
*/
public function handle($request, Closure $next)
{
$headers = [
'Access-Control-Allow-Origin' => $request->header('Origin'),
'Access-Control-Allow-Methods' => 'HEAD, POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers' => $request->header('Access-Control-Request-Headers'),
];
if ($request->isMethod('OPTIONS')) {
return response()->json('{"method":"OPTIONS"}', 200, $headers);
}
if ($request->header('Origin')) {
config(['access-control-origin' => $request->header('Origin')]);
}
return $next($request);
}
}
Don't forget to add this to your kernel.php in the $routeMiddleware array.
'cors' => \App\Http\Middleware\AddCorsHeaders::class,

Laravel 5 CORS middleware not working for group of routes

I am appling cors middleware to access json from some other domain.
This code works just fine :-
Route::get('api/authenticate', ['middleware' => 'cors', function() {
return Response::json(array('name' => 'Steve Jobs', 'state' => 'California'));
}]);
But when I apply it to :-
Route::group(['prefix' => 'api', 'middleware' => 'cors'], function()
{
Route::resource('authenticate', 'AuthenticateController', ['only' => ['index']]);
Route::post('authenticate', 'AuthenticateController#authenticate');
});
it gives me error in console,
No 'Access-Control-Allow-Origin' header is present on the requested resource
I have a have added Cors middleware, cors.php :-
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-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
}
}
Please help. Thanks.
I tried to find solution for mine as well when sending JWT into header. This is what resolved my case:
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
}
}

Resources