phputil / cors
phputil/router 的 CORS 中间件
v0.5.0
2024-06-29 19:10 UTC
Requires (Dev)
- kahlan/kahlan: ^5.2
- phpstan/phpstan: ^1.9
- phputil/router: ^0.3.0
- symfony/http-client: ^5.4
README
phputil/cors
🔌 CORS 中间件,用于 phputil/router
- 单元测试 ✔
- 文档齐全 📖
- 与 expressjs/cors 语法兼容 🎯
安装
需要 phputil/router v0.2.14+
composer require phputil/cors
使用方法
基本用法
require_once 'vendor/autoload.php'; use phputil\router\Router; use function phputil\cors\cors; // Step 1: Declare the namespace usage for the function. $app = new Router(); $app->use( cors() ); // Step 2: Invoke the function to use it as a middleware. $app->get( '/', function( $req, $res ) { $res->send( 'Hello' ); } ); $app->listen();
API
function cors( array|CorOptions $options ): callable;
$options
可以是来自类 CorOptions
的 数组 或 对象。所有其键/属性都是 可选的
origin
- 配置响应头
Access-Control-Allow-Origin
,指示允许的源。 - 允许的类型:
bool
、string
、array
。 true
,默认值,表示它反映Origin
请求头 - 即,它 允许任何源。false
将使其返回作为头值'*'
。- 非空的
string
值(例如'mydomain.com'
)将Origin
限制为定义的值。 - 非空的
array
值表示允许Origin
值。 - 当
Origin
请求头 未发送 并且选项origin
是true
时,它将返回*
- 旨在接受任何源。其他选项将阻止请求。 - 在使用凭据或 httpS 时使用
*
可能不会正常工作。尽可能发送请求头Origin
。
注意:不在配置列表中的源的返回状态码为 403
(禁止)。
credentials
- 配置响应头
Access-Control-Allow-Credentials
。 - 允许的类型:
bool
。 true
,默认值,使其包括头。false
使其省略头。- 如果您的应用程序使用 cookie 或某种类型的身份验证头,则此头部很重要。
methods
- 配置响应头
Access-Control-Allow-Methods
。 - 允许的类型:
string
、array
。 - 当请求头
Access-Control-Request-Method
未定义时,默认值 是GET,HEAD,OPTIONS,POST,PUT,DELETE,PATCH
。 - 当请求头
Access-Control-Request-Method
定义时,响应头Access-Control-Allow-Methods
将返回接收到的方法,除非定义了选项methods
。 - 在
string
中的 HTTP 方法必须用 逗号 分隔。
allowedHeaders
- 配置响应头
Access-Control-Allow-Headers
。 - 允许的类型:
string
、array
。 - 默认值 是
'*'
,表示接受任何请求头。 - 在
string
中的 HTTP 头必须用 逗号 分隔。
exposedHeaders
- 配置响应头
Access-Control-Expose-Headers
。 - 允许的类型:
string
、array
。 - 默认值 是
''
(空字符串),表示不包含头。 - 在
string
中的 HTTP 头必须用 逗号 分隔。
maxAge
- 配置响应头
Access-Control-Max-Age
。 - 允许的类型:
int
、null
。 - 默认值 是
null
,表示不包含头。 int
值表示预检请求可以缓存的时间(由浏览器缓存)。
示例
使用数组
$options = [ 'origin' => 'mydomain.com', 'methods' => 'GET,POST' ]; $app->use( cors( $options ) );
使用具有以 with
为前缀的可嵌套构建方法的类 CorOptions
use phputil\cors\CorsOptions; // Needed $options = ( new CorsOptions() ) ->withOrigin( 'mydomain.com' ) ->withMethods( 'GET,POST' ); $app->use( cors( $options ) );