sergioooo / cakephp-cors
CakePHP 4+ 插件,用于在您的应用程序中激活 CORS
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
This package is not auto-updated.
Last update: 2024-10-02 15:45:20 UTC
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 ]
允许来源 (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'] ]
允许凭据 (Access-Control-Allow-Credentials)
Access-Control-Allow-Credentials 头指示当凭据标志为 true 时,响应是否可以暴露。当用作对预请求响应的一部分时,这表示是否可以使用凭据发出实际请求。请注意,简单的 GET 请求不会被预请求,因此如果请求带有凭据的资源,如果此头不以资源返回,则浏览器会忽略响应,并且不会将其返回到 Web 内容。
'Cors' => [ 'AllowCredentials' => true, // OR 'AllowCredentials' => false, ]
允许方法 (Access-Control-Allow-Methods)
'Cors' => [ // string 'AllowMethods' => 'POST', // OR array 'AllowMethods' => ['GET', 'POST'], ]
允许头 (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'], ]
暴露头 (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'], ]
最大年龄 (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 ]