📜  laravel api enable cors - PHP (1)

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

Laravel API: Enabling CORS

CORS (Cross-Origin Resource Sharing) is a security feature implemented in all modern web-browsers that restricts web pages or web applications from accessing resources loaded from another domain. By default, Laravel API's are not designed to allow cross-origin requests. However, enabling CORS can be done easily through Laravel middleware.

Installing Required Packages

To enable CORS in Laravel, we need to install a package called laravel-cors. It can be installed via Composer by running the following command in the root directory of your Laravel project.

composer require barryvdh/laravel-cors
Updating CORS Configuration

After installing the laravel-cors package, we need to update the CORS configuration in the config/cors.php file. Here's an example of a basic configuration that allows any domain to send requests to the API.

return [
    'paths' => ['api/*'],

    'allowed_methods' => ['*'],

    'allowed_origins' => ['*'],

    'allowed_origins_patterns' => [],

    'allowed_headers' => ['*'],

    'exposed_headers' => false,

    'max_age' => false,

    'supports_credentials' => false,
];

The allowed_methods property determines which HTTP methods are allowed, allowed_origins property lists the domains that are allowed to make cross-origin requests, and the allowed_headers property is used to specify which HTTP headers are allowed to be used in a cross-origin request.

Enabling CORS Middleware

Now that our CORS configuration is set up, we need to enable CORS middleware in Laravel. We can do this by updating the App\Http\Kernel.php file and adding the following line to the $middleware property.

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

Once the above steps are completed, your Laravel API will be able to handle cross-origin requests. If you want to restrict CORS to specific domains, you can change the values in the allowed_origins property.

CORS is an essential security feature and is often enabled by default in most modern web frameworks. Enabling CORS in Laravel API is a straightforward process that allows any server to access your Laravel API resources from outside domains.