<?php
use CodeIgniter\Router\RouteCollection;
$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
$routes->resource('product');
$routes->options('product', static function () {
// Implement processing for normal non-preflight OPTIONS requests,
// if necessary.
$response = response();
$response->setStatusCode(204);
$response->setHeader('Allow:', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');
return $response;
$routes->options('product/(:any)', static function () {});
不要忘记为预检请求添加 OPTIONS 路由。因为如果路由不存在,控制器过滤器(必需过滤器除外)将不起作用。
CORS 过滤器处理所有预检请求,因此通常不会调用 OPTIONS 路由的闭包控制器。
在 Config\Filters 中设置
或者,你可以在 app/Config/Filters.php 中为 URI 路径设置 cors 过滤器。
<?php
namespace Config;
use CodeIgniter\Config\Filters as BaseFilters;
// ...
class Filters extends BaseFilters
// ...
public array $filters = [
// ...
'cors' => [
'before' => ['api/*'],
'after' => ['api/*'],
不要忘记为预检请求添加 OPTIONS 路由。因为如果路由不存在,控制器过滤器(必需过滤器除外)将不起作用。
<?php
use CodeIgniter\Router\RouteCollection;
$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
$routes->options('api/(:any)', static function () {});
CORS 过滤器处理所有预检请求,因此通常不会调用 OPTIONS 路由的闭包控制器。
配置完成后,你可以使用 spark 路由 命令检查路由和过滤器。
如果你想使用不同于默认配置的配置,请在 app/Config/Cors.php 中添加一个属性。
例如,添加 $api 属性。
<?php
namespace Config;
use CodeIgniter\Config\BaseConfig;
* Cross-Origin Resource Sharing (CORS) Configuration
* @see https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
class Cors extends BaseConfig
// ...
public array $api = [
'allowedOrigins' => ['https://app.example.com'],
'allowedOriginsPatterns' => [],
'supportsCredentials' => true,
'allowedHeaders' => ['Authorization', 'Content-Type'],
'exposedHeaders' => [],
'allowedMethods' => ['GET', 'POST', 'PUT', 'DELETE'],
'maxAge' => 7200,
属性名称(在上述示例中为 api)将成为配置名称。
然后,像 cors:api 一样将属性名称指定为过滤器参数:
<?php
use CodeIgniter\Router\RouteCollection;
$routes->group('api', ['filter' => 'cors:api'], static function (RouteCollection $routes): void {
$routes->resource('user');
$routes->options('user', static function () {});
$routes->options('user/(:any)', static function () {});
你也可以使用 过滤器参数。
class CodeIgniter\HTTP\Cors
CodeIgniter\HTTP\Cors::addResponseHeaders(RequestInterface $request, ResponseInterface $response) → ResponseInterface
$request (RequestInterface) – 请求实例
$response (ResponseInterface) – 响应实例
返回类型:
ResponseInterface
添加 CORS 的响应头。
CodeIgniter\HTTP\Cors::handlePreflightRequest(RequestInterface $request, ResponseInterface $response) → ResponseInterface
$request (RequestInterface) – 请求实例
$response (ResponseInterface) – 响应实例
返回类型:
ResponseInterface
处理预检请求。