manish-pareek/stack-cors

跨源资源共享库和中间件

dev-master / 2.0.x-dev 2022-08-15 12:58 UTC

This package is auto-updated.

Last update: 2024-09-15 17:44:15 UTC


README

库和中间件,用于您的 http-{基础,内核} 应用程序实现跨源资源共享。它试图实现W3C 建议关于跨源资源共享。

构建状态: .github/workflows/run-tests.yml

安装

使用 composer 安装 asm89/stack-cors

用法

此包可以作为库或作为 stack 中间件 使用。

选项

allowedMethodsallowedHeaders 选项不区分大小写。

您不需要同时提供 allowedOriginsallowedOriginsPatterns。如果传入的字符串之一匹配,则被视为有效的源。

如果向 allowedMethodsallowedOriginsallowedHeaders 提供了 ['*'],则允许所有方法/源/头。

示例:使用库

<?php

use Asm89\Stack\CorsService;

$cors = new CorsService([
    'allowedHeaders'         => ['x-allowed-header', 'x-other-allowed-header'],
    'allowedMethods'         => ['DELETE', 'GET', 'POST', 'PUT'],
    'allowedOrigins'         => ['https://'],
    'allowedOriginsPatterns' => ['/localhost:\d/'],
    'exposedHeaders'         => false,
    'maxAge'                 => false,
    'supportsCredentials'    => false,
]);

$cors->addActualRequestHeaders(Response $response, $origin);
$cors->handlePreflightRequest(Request $request);
$cors->isActualRequestAllowed(Request $request);
$cors->isCorsRequest(Request $request);
$cors->isPreflightRequest(Request $request);

示例:使用中间件

<?php

use Asm89\Stack\Cors;

$app = new Cors($app, [
    // you can use ['*'] to allow any headers
    'allowedHeaders'      => ['x-allowed-header', 'x-other-allowed-header'],
    // you can use ['*'] to allow any methods
    'allowedMethods'      => ['DELETE', 'GET', 'POST', 'PUT'],
    // you can use ['*'] to allow requests from any origin
    'allowedOrigins'      => ['localhost'],
    // you can enter regexes that are matched to the origin request header
    'allowedOriginsPatterns' => ['/localhost:\d/'],
    'exposedHeaders'      => false,
    'maxAge'              => false,
    'supportsCredentials' => false,
]);