📜  laravel 5.8 cors - PHP (1)

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

Laravel 5.8 CORS

CORS (Cross-Origin Resource Sharing) is a security feature implemented by browsers that blocks web pages from making requests to a different domain than the one from which the web page was served. This can cause issues when building web applications that rely on server-to-server communication, such as APIs.

Laravel 5.8 includes a built-in middleware for handling CORS requests, making it easier to build modern web applications.

Installation

To enable the CORS middleware in your Laravel 5.8 application, you will need to perform the following steps:

  1. Install the fruitcake/laravel-cors package using Composer:
composer require fruitcake/laravel-cors
  1. Register the CorsMiddleware in your app/Http/Kernel.php file:
protected $middlewareGroups = [
    'web' => [
        // ...
        \Fruitcake\Cors\HandleCors::class,
    ],

    // ...
];
Configuration

The fruitcake/laravel-cors package includes a default configuration suitable for most web applications, but you can customize the middleware behavior by publishing the configuration to your application:

php artisan vendor:publish --provider="Fruitcake\Cors\CorsServiceProvider" --tag="config"

This will create a config/cors.php file where you can define the allowed origins, methods, and headers, among other options.

Usage

Once the CORS middleware is registered and configured in your Laravel 5.8 application, it will automatically handle CORS requests for all routes, unless you specify otherwise.

If you need to disable the CORS middleware for a specific route, you can do so using the withoutMiddleware method:

Route::get('/', function () {
    //
})->withoutMiddleware([\Fruitcake\Cors\HandleCors::class]);
Conclusion

CORS is an important security feature implemented by browsers that can cause issues when building web applications that rely on server-to-server communication. With Laravel 5.8, handling CORS requests is made easier with the built-in middleware provided by the fruitcake/laravel-cors package.