php-laravelHow do I enable CORS in a Laravel PHP application?
To enable CORS in a Laravel PHP application, you must first modify the config/cors.php
file. This file contains the configuration options for the Laravel CORS package.
You can then use the \Barryvdh\Cors\HandleCors
middleware to add CORS headers to your routes. For example:
Route::middleware('\Barryvdh\Cors\HandleCors')->get('/api', function () {
return response('Hello World', 200)
->header('Content-Type', 'text/plain');
});
The HandleCors
middleware will add the following CORS headers to the response:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: *
Access-Control-Allow-Headers: *
You can also use the \Barryvdh\Cors\CorsServiceProvider
service provider to configure the CORS package. This allows you to customize the CORS headers for each route, and also set the allowed origins, methods, and headers. For example:
Cors::setHeader('Access-Control-Allow-Origin', 'http://example.com');
You can find more information about configuring CORS in the Laravel CORS documentation.
More of Php Laravel
- How can I use the PHP Zipstream library in a Laravel project?
- How do I set up a .gitlab-ci.yml file for a Laravel project using PHP?
- How can I use the @yield directive in PHP Laravel?
- How can I use the Laravel WhereIn method in PHP?
- ¿Cómo configurar PHP y Laravel desde cero?
- How can I use PHP, Laravel, and Vue together to create a web application?
- How can I get the current year in PHP Laravel?
- How can I use PHP Laravel's ZipArchive library to create a zip file?
- How can I use PHP and Laravel together?
- How do I configure Xdebug in the php.ini file for a Laravel project?
See more codes...