ozee31 / cakephp-cors
一个用于在您的应用程序中激活cors域的CakePHP(3.3.x)插件
Requires
- php: >=7.2.0
- cakephp/cakephp: ^4.0
- psr/http-server-handler: ^1.0
- psr/http-server-middleware: ^1.0
Requires (Dev)
- cakephp/cakephp-codesniffer: ^4.0
- phpunit/phpunit: ~8.5.0
README
一个用于在您的应用程序中通过 中间件 激活cors域的CakePHP (4+) 插件。
对于cake 3.3+ 使用分支 cake-3
要求
- PHP版本7.2或更高
- CakePhp 4.0或更高
安装
您可以使用 composer 将此插件安装到您的CakePHP应用程序中。
安装composer包的推荐方法是
composer require ozee31/cakephp-cors
快速入门
加载插件
// In src/Application.php public function bootstrap(): void { // code ... $this->addPlugin('Cors'); }
默认情况下,该插件为所有来源、所有方法和所有头部授权cors,并缓存一天。
配置
默认配置
<?php [ 'AllowOrigin' => true, // accept all origin 'AllowCredentials' => true, 'AllowMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'], // accept all HTTP methods 'AllowHeaders' => true, // accept all headers 'ExposeHeaders' => false, // don't accept personal headers 'MaxAge' => 86400, // cache for 1 day 'exceptionRenderer' => 'Cors\Error\AppExceptionRenderer', // Use ExeptionRenderer class of plugin
更改配置
在 app.php
中添加
'Cors' => [ // My Config ]
AllowOrigin (Access-Control-Allow-Origin)
返回的资源可能有一个Access-Control-Allow-Origin头部,其语法如下
'Cors' => [ // Accept all origins 'AllowOrigin' => true, // OR 'AllowOrigin' => '*', // Accept one origin 'AllowOrigin' => 'http://flavienbeninca.fr' // Accept many origins 'AllowOrigin' => ['http://flavienbeninca.fr', 'http://google.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' => [ // string 'AllowMethods' => 'POST', // OR 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, ]
exceptionRenderer
此选项重载了位于 app.php
中的默认 exceptionRenderer
。
默认情况下,此类从 Error.exceptionRenderer
继承,以添加 CORS 头部
如果您不想重载 exceptionRenderer,您必须编写
'Cors' => [ 'exceptionRenderer' => false ]