The frontend JavaScript code for a web application served from a domain
uses Http Request to make a request for the API in the backend domain. For
security reasons, browsers restrict cross-origin HTTP requests initiated within
scripts. So how do we resolve it?
The main cause is because, Cross-Origin Resource Sharing (CORS) is a mechanism that uses additional
HTTP headers to tell a browser to let a web application running at one origin
(domain) have permission to access selected resources from a server at a
different origin. A web application makes a cross-origin HTTP request when it
requests a resource that has a different origin (domain, protocol, and port)
than its own origin.
Here is the Solution for this issue:
A
web application using those APIs can only request HTTP resources from the same
origin the application was loaded from, unless the response from the other
origin includes the right CORS headers. The CORS mechanism supports secure
cross-origin requests and data transfers between browsers and web servers.
Modern browsers use CORS in an API container such as XMLHttpRequest or Fetch to
help mitigate the risks of cross-origin HTTP requests.
“In Laravel framework the laravel-cors package allows you to send
Cross-Origin Resource Sharing headers with Laravel middle-ware configuration.”
What is laravel-cors?
Features
- Handles CORS pre-flight OPTIONS requests
- Adds CORS headers to your response
Installation
Require the barryvdh/laravel-cors package in composer.json file
and update your dependencies:
$ composer require barryvdh/laravel-cors
For Laravel version < 5.5, you also need to add Cors\ServiceProvider
to your config/app.php providers array:
Barryvdh\Cors\ServiceProvider::class,
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,
];
Configuration
The defaults are set in config/cors.php. Copy this file to your
own config directory to modify the values.
Note: When using custom headers, like X-Auth-Token or X-Requested-With,
you must set the allowedHeaders to include those headers. You can also
set it to array('*') to allow all custom headers
return [
/*
|--------------------------------------------------------------------------
| Laravel CORS
|--------------------------------------------------------------------------
| allowedOrigins, allowedHeaders and allowedMethods can be set to
array('*')
| to accept any value.
|
*/
'supportsCredentials' => false,
'allowedOrigins' => ['*'],
'allowedOriginsPatterns' => [],
'allowedHeaders' => ['*'],
'allowedMethods' => ['*'],
'exposedHeaders' => [],
'maxAge' => 0,
];
Comments
Post a Comment