davidecesarano/embryo-cors

PSR-15 to implement Cross-Origin Resource Sharing (CORS).

1.0.1 2021-06-11 08:43 UTC

This package is auto-updated.

Last update: 2024-10-25 16:47:03 UTC


README

Simple PSR-15 Middleware to implement Cross-Origin Resource Sharing (CORS).

Requirements

Install

Using Composer:

$ composer require davidecesarano/embryo-cors

Usage

use Embryo\CORS\CorsMiddleware;
use Embryo\Http\Factory\{ResponseFactory, ServerRequestFactory};
use Embryo\Http\Server\RequestHandler;

// Set options
$allowed_origins = ['*'];
$allowed_methods = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'];
$allowed_headers = ['Content-Type', 'Accept', 'Origin', 'Authorization'];
$exposed_headers = [];
$max_age = 0;
$supports_credentials = false;

// Add middleware to dispatcher
$requestHandler = new RequestHandler([
    (new CorsMiddleware)
        ->setAllowedOrigins($allowed_origins)
        ->setAllowedMethods($allowed_methods)
        ->setAllowedHeaders($allowed_headers)
        ->setExposedHeaders($exposed_headers)
        ->setMaxAge($max_age)
        ->setSupportsCredentials($supports_credentials)
]);

// Set PSR Request and Response
$request = (new ServerRequestFactory)->createServerRequestFromServer();
$response = (new ResponseFactory)->createResponse(200);

$response = $requestHandler->dispatch($request, $response);