makise-co / stack-cors
跨源资源共享库和中间件
v2.0.7
2021-11-29 22:25 UTC
Requires
- php: >=7.4
- makise-co/framework: ~1.0.0
- psr/http-message: ^1.0.1
- psr/http-server-middleware: ^1.0.1
Requires (Dev)
- phpunit/phpunit: ^6|^7|^8|^9
- squizlabs/php_codesniffer: ^3.5
README
是 https://github.com/asm89/stack-cors 的分支,允许在 Makise 框架中使用原始包。
库和中间件,使您的 http-{基础,内核} 应用程序能够实现跨源资源共享。它试图实现 W3C 建议的 跨源资源共享。
安装
使用 composer 安装 makise-co/stack-cors
。
使用
- 在您的配置目录中创建
cors.php
配置文件 - 将
CorsServiceProvider
添加到config/app.php
的 "providers" 部分 - 将
CorsMiddleware
添加到config/http.php
的 "middleware" 部分
选项
allowedMethods 和 allowedHeaders 选项不区分大小写。
您不需要同时提供 allowedOrigins 和 allowedOriginsPatterns。如果传入的字符串之一匹配,则认为是一个有效的来源。
如果向 allowedMethods、allowedOrigins 或 allowedHeaders 提供了 array('*')
,则允许所有方法/来源/头。
示例:允许所有路径上的 CORS 的配置
return [ /* * You can enable CORS for 1 or multiple paths. * Example: ['api/*'] */ 'paths' => ['*'], /* * Matches the request method. `[*]` allows all methods. */ 'allowedMethods' => ['*'], /* * Matches the request origin. `[*]` allows all origins. */ 'allowedOrigins' => ['*'], /* * Matches the request origin with, similar to `Request::is()` */ 'allowedOriginsPatterns' => [], /* * Sets the Access-Control-Allow-Headers response header. `[*]` allows all headers. */ 'allowedHeaders' => ['*'], /* * Sets the Access-Control-Expose-Headers response header. */ 'exposedHeaders' => false, /* * Sets the Access-Control-Max-Age response header. */ 'maxAge' => 600, /* * Sets the Access-Control-Allow-Credentials header. */ 'supportsCredentials' => true, ];
示例:使用库
<?php use Asm89\Stack\CorsService; $cors = new CorsService(array( 'allowedHeaders' => array('x-allowed-header', 'x-other-allowed-header'), 'allowedMethods' => array('DELETE', 'GET', 'POST', 'PUT'), 'allowedOrigins' => array('https://'), 'allowedOriginsPatterns' => array('/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);