Reputation: 457
I have a Laravel 7 application and I'm trying to access an external URL in a Bootstrap model window. When I use the below jQuery function, on button click, I want to load the model and show the external website.
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load('http://***.com');
});
I get the bellow error.
Access to XMLHttpRequest at 'http://****' from origin 'http://****' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.
I have searched and found one solution to use middleware. I created the middleware file in app\http\Middleware\Cors.php
.
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',
'Accept,Authorization,Content-Type');
}
After that I have added the following in app\http\Kernel.php
.
protected $middleware = [
....
...
\App\Http\Middleware\Cors::class,
];
But I still get the same error. How can I fix this error?
Upvotes: 0
Views: 2019
Reputation: 2773
There can be CORS on Both side on 1 API side at external URL. ( this you cannot change) 2 At your bootstrap Laravel application.( this you can change)
$('#myModal').on('show.bs.modal', function (e) {
$(this).find('.modal-body').load('http://***.com');
});
This is just a Jquery code. Can you convert this code to some server side language like php? Remember CORS can be overridden by server side code.
Upvotes: 0
Reputation: 101
Laravel 7 has been released in March and provides built-in support for CORS so developers don't need to use third-party packages to enable CORS in their Laravel apps.
You can use config/cors.php file for your cors settings.
For more details please follow the link - https://www.techiediaries.com/laravel/laravel-7-6-cors-example-and-tutorial/
Upvotes: 1
Reputation: 688
Since you didn't explicitly mention it I'll assume you didn't do this:
you have to enable CORS for every route you want to use it with.
According to:
https://github.com/fruitcake/laravel-cors
Upvotes: 0