CodeIgniter4 CORS 跨域问题

当使用前后端分离,并且前端后端域名不统一时,我遇到了跨域的问题

1
Access to XMLHttpRequest at http://localhost/api/login from origin http://localhost:8010 has been blocked by CORS policy: Response to preflight request doesnt pass access control check: NoAccess-Control-Allow-Origin header is present on the requested resource.```
1
Access to XMLHttpRequest at http://localhost/api/login from origin http://localhost:8010 has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response.

我们只需要在返回的 response 中添加 header就可以了

首先我们创建一个 Filter 用来批量在生成的 response 中添加 headers

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
App\Filters\Api.php
<?php
namespace App\Filters;

use CodeIgniter\Filters\FilterInterface;
use CodeIgniter\HTTP\RequestInterface;
use CodeIgniter\HTTP\ResponseInterface;

class Api implements FilterInterface
{
public function before(RequestInterface $requset)
{

}

public function after(RequestInterface $request, ResponseInterface $response)
{
$response->setHeader(Access-Control-Allow-Origin, *);
$response->setHeader(Access-Control-Allow-Headers, Content-Type);
return $response;
}
}

接下来我们将注册并配置 App\Filters\Api::class, 编辑配置文件 App\Config\Filters.php

1
2
3
4
5
6
7
8
...
public $aliases = [
csrf => \CodeIgniter\Filters\CSRF::class,
toolbar => \CodeIgniter\Filters\DebugToolbar::class,
honeypot => \CodeIgniter\Filters\Honeypot::class,
api => \App\Filters\Api::class, //注册 Filter
];
...

配置该 filter 对哪些 uri 生效

public $filters = [
        api => [
            after =>[
                api/*,
            ]
        ]
    ];

至此,在每个路径为 api/* 的请求返回前,就会执行 after 中的代码,添加 headers