📌  相关文章
📜  access-control-allow-origin php laravel - PHP (1)

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

Access-Control-Allow-Origin in PHP Laravel

Access-Control-Allow-Origin is a HTTP header used to specify which domains are allowed to access a particular resource. It is an important security feature implemented on the server-side to protect web resources from unauthorized access.

In Laravel, Access-Control-Allow-Origin can be added to server responses using the following ways:

Option 1: Adding Headers Middleware

By default, Laravel provides a middleware called headers which is used to add HTTP headers to responses. To add Access-Control-Allow-Origin header to responses, you can update the app/Http/Middleware/Headers.php file as follows:

<?php

namespace App\Http\Middleware;

use Closure;

class Headers
{
    /**
     * Add the headers to the response.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Illuminate\Http\Response  $response
     * @return \Illuminate\Http\Response
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('Access-Control-Allow-Origin', '*');

        return $response;
    }
}

Once you have updated the middleware, go ahead and add it to the route(s) or globally in Kernel.php to apply the headers to all responses.

Option 2: Using a Package

If you don't want to manually write middleware, you can use a package like barryvdh/laravel-cors to handle CORS in Laravel. Here's how to install and use the package:

  1. Install the package via Composer:

    composer require barryvdh/laravel-cors
    
  2. Register the service provider in your config/app.php file:

    'providers' => [
        // ...
        Barryvdh\Cors\ServiceProvider::class,
    ],
    
  3. Add CORS middleware to your middleware stack in app/Http/Kernel.php file:

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

That's it! Now, CORS will be handled for all requests in your application.

Conclusion

By adding Access-Control-Allow-Origin header to server responses, you can control which domains can access your resources. Whether you choose to use middleware or a package, Laravel makes it easy to implement CORS in your application.