📜  laravel-cors - PHP (1)

📅  最后修改于: 2023-12-03 15:32:37.150000             🧑  作者: Mango

Laravel-CORS

Laravel-CORS is a package for Laravel that allows you to add CORS (Cross-Origin Resource Sharing) headers to your responses. This package provides a simple middleware that you can use to enable CORS for your Laravel API.

Installation

To install Laravel-CORS, you can use Composer:

composer require fruitcake/laravel-cors

After installing the package, you will need to register the middleware in your Kernel.php file:

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];

Once registered, the middleware will automatically add the appropriate headers to your API responses.

Configuration

You can customize the behavior of Laravel-CORS by publishing the configuration file:

php artisan vendor:publish --tag=laravel-cors

This will create a config/cors.php file that you can modify to your needs. The available options include:

  • allowed_origins: a list of allowed origins. You can use * to allow all origins.
  • allowed_methods: a list of allowed HTTP methods. By default, GET, POST, PUT, PATCH, DELETE are allowed.
  • allowed_headers: a list of allowed HTTP headers. By default, Authorization, Content-Type, and Accept are allowed.
  • exposed_headers: a list of headers that the client can access in the response.
  • max_age: the maximum amount of time that the client can cache your CORS response.
  • supports_credentials: whether or not the API supports cookies in cross-origin requests.
Usage

To enable CORS for your Laravel API, simply add the HandleCors middleware to your routes or controllers. For example:

Route::middleware('cors')->group(function () {
    Route::get('/my-api', 'MyApiController@index');
});

This will add the necessary headers to the response for the /my-api endpoint.

You can also use the middleware globally by adding it to your Kernel.php file:

protected $middleware = [
    // ...
    \Fruitcake\Cors\HandleCors::class,
];
Conclusion

Laravel-CORS is a simple and easy-to-use package for enabling CORS in your Laravel API. By adding the HandleCors middleware to your routes, you can add the necessary headers to your responses and allow cross-origin requests from any domain.