phputil/cors

phputil/router 的 CORS 中间件

v0.5.0 2024-06-29 19:10 UTC

This package is auto-updated.

Last update: 2024-08-29 19:32:03 UTC


README

Version Build License

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,指示允许的源。
  • 允许的类型:boolstringarray
  • true默认值,表示它反映 Origin 请求头 - 即,它 允许任何源
  • false 将使其返回作为头值 '*'
  • 非空的 string 值(例如 'mydomain.com')将 Origin 限制为定义的值。
  • 非空的 array 值表示允许 Origin 值。
  • Origin 请求头 未发送 并且选项 origintrue 时,它将返回 * - 旨在接受任何源。其他选项将阻止请求。
  • 在使用凭据或 httpS 时使用 * 可能不会正常工作。尽可能发送请求头 Origin

注意:不在配置列表中的源的返回状态码为 403(禁止)。

credentials

  • 配置响应头 Access-Control-Allow-Credentials
  • 允许的类型:bool
  • true默认值,使其包括头。
  • false 使其省略头。
  • 如果您的应用程序使用 cookie 或某种类型的身份验证头,则此头部很重要。

methods

  • 配置响应头 Access-Control-Allow-Methods
  • 允许的类型:stringarray
  • 当请求头 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
  • 允许的类型:stringarray
  • 默认值'*',表示接受任何请求头。
  • string 中的 HTTP 头必须用 逗号 分隔。

exposedHeaders

  • 配置响应头 Access-Control-Expose-Headers
  • 允许的类型:stringarray
  • 默认值''(空字符串),表示不包含头。
  • string 中的 HTTP 头必须用 逗号 分隔。

maxAge

  • 配置响应头 Access-Control-Max-Age
  • 允许的类型:intnull
  • 默认值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 ) );

许可

MIT 许可协议 © Thiago Delgado Pinto