Servers are used to host web pages, applications, images, fonts, and
much more. When you use a web browser, you are likely attempting to
access a distinct website (hosted on a server). Websites often request
these hosted resources from different locations (servers) on the
Internet. Security policies on servers mitigate the risks associated
with requesting assets hosted on different server. Let's take a look
at an example of a security policy: same-origin.
The same-origin policy is very restrictive. Under this policy, a
document (i.e., like a web page) hosted on server A can only interact
with other documents that are also on server A. In short, the
same-origin policy enforces that documents that interact with each
other have the same origin.
Check this CORS library made for Laravel usage.
Installation is easy:
$ composer require barryvdh/laravel-cors
$ php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
The defaults are set in config/cors.php
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
|
| allowedOrigins, allowedHeaders and allowedMethods can be set to array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedHeaders' => ['Content-Type', 'X-Requested-With'],
'allowedMethods' => ['*'], // ex: ['GET', 'POST', 'PUT', 'DELETE']
'exposedHeaders' => [],
'maxAge' => 0,
];
allowedOrigins, allowedHeaders
and allowedMethods
can be set to array('*')
to accept any value.
To allow CORS for all your routes, add the HandleCors middleware in the $middleware
property of app/Http/Kernel.php
class:
protected $middleware = [
// ...
\Barryvdh\Cors\HandleCors::class,
];
If you want to allow CORS on a specific middleware group or route, add the HandleCors middleware to your group:
protected $middlewareGroups = [
'web' => [
// ...
],
'api' => [
// ...
\Barryvdh\Cors\HandleCors::class,
],
];
https://www.codecademy.com/articles/what-is-cors
vendor
.api/routes/api.php
is the file to edit - Laravel used to have all routes inroutes.php
, but it's not split up into web and API versions. – ceejayozvue-cli
? – ljubadr