rrd108 / cakephp-cors
一个用于在您的应用程序中激活CORS域的CakePHP插件
Requires
- cakephp/cakephp: ^5.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- cakephp/cakephp-codesniffer: @stable
- phpunit/phpunit: ^10.1
README
一个用于在您的应用程序中通过中间件激活CORS域的CakePHP 5插件。
由于原项目已归档,因此从ozee31/cakephp-cors 分支创建。
安装
您可以使用 composer 将此插件安装到您的CakePHP应用程序中。
安装composer包的推荐方式是
composer require rrd108/cakephp-cors
然后使用以下命令加载插件
bin/cake plugin load Rrd108/Cors
更改默认设置
默认情况下,插件为所有来源、所有方法和所有头授权CORS,并缓存一天。如果您对默认设置感到满意,可以跳过此部分。
如果您想更改任何值,请创建项目目录下的自己的 config/cors.php
文件。在您的配置文件中,您应该只使用您想更改的键。它将与默认配置合并。例如,如果您对所有选项都满意,除了默认的 AllowOrigin
,那么您必须将此放入您的配置文件中。
'Cors' => [ 'AllowOrigin' => ['https://:5173', 'https://example.com'], ]
AllowOrigin (Access-Control-Allow-Origin)
返回的资源可能有一个Access-Control-Allow-Origin头,其语法如下
'Cors' => [ // Accept all origins 'AllowOrigin' => true, // OR 'AllowOrigin' => '*', // Accept one origin 'AllowOrigin' => 'http://webmania.cc' // Accept many origins 'AllowOrigin' => ['http://webmania.cc', 'https://example.com'] ]
AllowCredentials (Access-Control-Allow-Credentials)
Access-Control-Allow-Credentials头指示当credentials标志为true时,是否可以暴露对请求的响应。当用作对预检请求的响应的一部分时,这表示是否可以使用凭据执行实际请求。请注意,简单的GET请求不会进行预检,因此如果请求带有凭据的资源,并且此头不随资源返回,则浏览器将忽略响应并将其返回给Web内容。
'Cors' => [ 'AllowCredentials' => true, // OR 'AllowCredentials' => false, ]
AllowMethods (Access-Control-Allow-Methods)
'Cors' => [ // shoud be an array 'AllowMethods' => ['GET', 'POST'], ]
AllowHeaders (Access-Control-Allow-Headers)
Access-Control-Allow-Headers头用于对预检请求的响应,以指示在执行实际请求时可以使用哪些HTTP头。
'Cors' => [ // accept all headers 'AllowHeaders' => true, // accept just authorization 'AllowHeaders' => 'authorization', // accept many headers 'AllowHeaders' => ['authorization', 'other-header'], ]
ExposeHeaders (Access-Control-Expose-Headers)
Access-Control-Expose-Headers头允许服务器将浏览器允许访问的头列表为白名单。例如
'Cors' => [ // nothing 'ExposeHeaders' => false, // string 'ExposeHeaders' => 'X-My-Custom-Header', // array 'ExposeHeaders' => ['X-My-Custom-Header', 'X-Another-Custom-Header'], ]
MaxAge (Access-Control-Max-Age)
Access-Control-Max-Age头指示预检请求的结果可以缓存多长时间。有关预检请求的示例,请参阅上面的示例。
'Cors' => [ // no cache 'MaxAge' => false, // 1 hour 'MaxAge' => 3600, // 1 day 'MaxAge' => 86400, ]