How to solve CORS error in laravel?
Cross-Origin Resource Sharing (CORS) is a standard that allows a server to relax the same-origin policy. This is used to explicitly allow some cross-origin requests while rejecting others.
CORS errors occur when a webpage makes a request to a different domain than the one that served the page, and the server responds with an HTTP error because the "Origin" header in the request is not allowed by the server's CORS configuration.
If the CORS configuration isn't set up correctly, the browser console will present an error like "Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at $somesite" indicating that the request was blocked due to violating the CORS security rules.
We will be making a middleware so we can use it based on routes or global, But you can pass all this headers in API or in .htaccess
php artisan make:middleware Cors
Now a middleware named Cors.php will be generated in : app/Http/Middleware/Cors.php
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', '*')
->header('Access-Control-Allow-Credentials', true)
->header('Access-Control-Allow-Headers', '*')
->header('Accept', 'application/json');
}
}
Note : Some browser do not support ' * ' logic, So to solve that you need to specify parameters.
<?php
namespace App\Http\Middleware;
use Closure;
class Cors
{
public function handle($request, Closure $next)
{
return $next($request)
->header('Access-Control-Allow-Origin', 'url_here')
->header('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,OPTIONS')
->header('Access-Control-Allow-Credentials', true)
->header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Token-Auth,Authorization')
->header('Accept', 'application/json');
}
}
For security reasons, specifics about what went wrong with a CORS request are not available to JavaScript code. The only way to determine what specifically went wrong is to look at the browser's console for details.
Tags
Related Posts
How to save image from a url in laravel?
How to run laravel 10 project without artisan serve?
How to solve CORS error in laravel?
How to upload file in laravel through an API?
How to use seeder in laravel?
Most Useful Laravel Commands
How to create multi auth in laravel with 2 different login page?
How to create a custom helper file and function in Laravel?
How to us factory in laravel?
How to upload image in summernote laravel?