

本次更新内容的具体使用
PSR-15 中间件
先创建一个实例:
use MedzCorsPSRCorsMiddleware; // Settings. $settings = [ 'allow-credentials' => false, 'allow-headers' => ['*'], 'expose-headers' => [], 'origins' => ['*'], 'methods' => ['*'], 'max-age' => 0, ]; // $cors = new MedzCorsCors($settings); // Create CORS instance. // Create CORS middleware instance $middleware = new CorsMiddleware($settings /* $cors */ /* , true */ /* 是否仅处理预检 */); // TODO.
可以看出,新版本可以直接从中间件构造参数进行传递设置了,之前版本必须传递一个 MedzCorsCors 实例,当然,新版本也可以直接传递实例。第二个参数可以进行配置是否仅处理预检请求,默认是处理全部请求。
Swoft 中间件
在配置文件 config/properties/app.php 中进行如下配置:
'components' => [ 'custom' => [ 'Medz\Cors\Swoft\', ], ], 'cors' => [ 'onlyPreflight' => false, // 是否仅 OPTIONS 预检请求才进行跨域信息附加 'settings' => [ /// ... 参考 README 中的 PSR-7 ], ],
全局使用
打开 app/config/beans/base.php 配置如下:
'serverDispatcher' => [ 'middlewares' => [ MedzCorsSwoftCorsMiddleware::class, ], ],
通过注解使用
通过 @Middleware 和 @Middlewares, 可以很方便的配置中间件到当前的 Controller 和 Action 内。
● 当将此注解应用于 Controller 上,则作用域为整个 Controller
● 将此注解应用于 Action 上,则作用域仅为当前的 Action
use SwoftHttpServerBeanAnnotationController;
use SwoftHttpMessageBeanAnnotationMiddleware;
use SwoftHttpServerBeanAnnotationRequestMapping;
use MedzCorsSwoftCorsMiddleware;
/**
 * Setting Controller middleware.
 * 
 * @Controller("middleware")
 * @Middleware(CorsMiddleware::class)
 */
class CorsOneController
{
 //
}
/**
 * Setting Action middleware.
 */
class CorsTwoController
{
 /**
 * @RequestMapping()
 * @Middleware(CorsMiddleware::class)
 */
 public function corsAction(): array
 {
 return [
 'message' => 'The action using CORS.'
 ];
 }
}其他
CORS 项目地址 https://github.com/medz/cors ,如果喜欢,欢迎 Star 欢迎 Issues 欢迎 PR。
Seven 的代码太渣,欢迎关注我的新拓展包 medz/cors 解决 PHP 项目程序设置跨域需求。
