CORS in CodeIgniter 4, the easy way - 08

Video thumbnail

Let's see how we can connect to the Rest API in CodeIgniter from an external project, in this example, it would be the application created in Vue.
让我们看看如何从外部项目连接到 CodeIgniter 中的 Rest API,在这个例子中,它将是在 Vue 中创建的应用程序。

There are many ways to configure CORS in CodeIgniter 4, let's see the simplest way, which would be by modifying the public/index.php file:
在 CodeIgniter 4 中配置 CORS 的方法有很多种,让我们看看最简单的方法,就是修改 public/index.php 文件:

public\index.php  公共\index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
***

This is the one we will use at least for the moment due to its simplicity; in the previous lines we are indicating that from any source (*):
由于它的简单性,我们至少暂时会使用这个版本;在前面的几行中,我们指出了来自任何来源 (*):

header('Access-Control-Allow-Origin: *');

Can make HTTP requests; obviously this is very risky and we will only leave this configuration when in development mode, but the * means everywhere; you can also put the development domain:
可以发出 HTTP 请求;显然这是非常危险的,我们只会在开发模式下保留这个配置,但 * 意味着无处不在;你也可以把开发域:

header('Access-Control-Allow-Origin: http://localhost:5173');

With the second line:  使用第二行:

header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');

We indicate the types of HTTP methods allowed, although according to tests, you can do without the second line. With this, you will see that it no longer returns the previous error.
我们指出了允许的 HTTP 方法类型,尽管根据测试,您可以不用第二行。有了这个,你会看到它不再返回以前的错误。

As we will see later, when sending a request of type POST, PUT, PATCH, the previous error appears again, this is because a request is sent prior to the POST called preflight, which verifies the CORS configurations and which must have a configuration like the following:
正如我们稍后将看到的,当发送 POST、PUT、PATCH 类型的请求时,之前的错误会再次出现,这是因为在 POST 之前发送了一个名为 preflight 的请求,该请求验证 CORS 配置,并且必须具有如下所示的配置:

public\index.php  公共\index.php

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, POST, PUT, DELETE');
***
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
   header('Access-Control-Allow-Origin: *');
   header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
   header('Access-Control-Allow-Headers: token, Content-Type');
   header('Access-Control-Max-Age: 1728000');
   header('Content-Length: 0');
   header('Content-Type: text/plain');
   die();
}

That they practically do not exist, notice. It has been a long time since it was updated and so on, and in principle with this package we could easily configure them, although I do not know if this is for the three. No, here it says four. There we install it, we continue, we add, in this case there is a filter, we indicate what the routes of our Api are going to be and well, that would be practically everything and there we could use it without any problem, but it is not necessary, it is an outdated package, therefore, if you do not update it, I advise against its use because you are using a package without maintenance. And at some point it will fail, but notice that
请注意,它们实际上不存在。更新等已经很长时间了,原则上有了这个包,我们可以轻松配置它们,尽管我不知道这是否适用于三个。不,这里说四个。我们在那里安装它,我们继续,我们添加,在这种情况下有一个过滤器,我们指示我们的 Api 的路由将是什么,嗯,这几乎是所有内容,我们可以毫无问题地使用它,但这不是必需的,它是一个过时的包,因此,如果您不更新它,我建议您不要使用它,因为您使用的是没有维护的包。在某些时候它会失败,但请注意

https://github.com/agungsugiarto/codeigniter4-cors

Starting with version 4.5.0, that is to say, quite advanced, once version 4 was released, they decided to implement the use of CORS and this is why I say that sometimes CodeIgniter is a slightly strange framework in that sense, we will do this configuration later, but again, since it is simple, it was literally just adding a line of code, so I preferred not to complicate things too much with this, which is not very complicated either, but notice that it is similar to the package:
从 4.5.0 版本开始,也就是说,相当高级,一旦版本 4 发布,他们就决定实现 CORS 的使用,这就是为什么我说有时 CodeIgniter 在这个意义上是一个有点奇怪的框架,我们稍后会做这个配置,但同样,因为它很简单,它实际上只是添加了一行代码,所以我宁愿不要让事情复杂太多,这也不是很复杂,但请注意它与包类似:

https://codeigniter.com/user_guide/libraries/cors.html

CORS in CodeIgniter 4, the right way
CodeIgniter 4 中的 CORS,正确的方法

Video thumbnail

Now that the implementation with viw is finally finished, at least the part that I wanted to implement, the next thing we want to do is configure the cors in the correct way, so to speak, so as I was telling you, it is a feature that was not released when CodeIgniter 4 came out, as indicated here, it came out from version 4. 5. Here are a few criticisms before showing the implementation, I want to comment on a few things.

Remember to comment or remove the implementation that we showed above to test this implementation.

This part of the documentation is a bit abstract and the documentation does not help, so I understand that what I am indicating here is what was the prel request, that is, the request before the request, again before making this request, for example, this one about movies, it makes a previous request according to the tests we did previously, which was when we configured the rest of the headers in our Index, so I understand that is why it does not ask for them, it should not be done internally. But well, that is how it works, I don't know, a little bit of my opinion, I am giving you here a little bit of my opinion and also the implementation.

used by Vue:

app/Config/Cors.php

'allowedOrigins' => ['http://localhost:5173'],

Or if you want it to be open to all routes:

app/Config/Cors.php

'allowedOrigins' => ['*'], // Allows any origin.

Create a bundle for your API routes and CORS middleware:

app/Config/Routes.php

$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
  
   $routes->group('api', ['namespace' => '\App\Controllers\Api'], function ($routes) {
       $routes->resource('pelicula');
       $routes->resource('categoria');
   });
   
   $routes->options('api/(:any)', static function () {});
});

This route:

$routes->options('api/(:any)', static function () {});

This is for Preflight Requests, that is, a control request before the requests we make to the API.

Also, you must expose the methods that can be used:

app/Config/Cors.php

'allowedMethods' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE'],

You can also try by:

app/Config/Routes.php

$routes->group('', ['filter' => 'cors'], static function (RouteCollection $routes): void {
  
   $routes->group('api', ['namespace' => '\App\Controllers\Api'], function ($routes) {
       $routes->resource('pelicula');
       $routes->resource('categoria');
   });
   $routes->options('api/(:any)', static function () {
       // Implement processing for normal non-preflight OPTIONS requests,
       // if necessary.
       $response = response();
       $response->setStatusCode(200);
       $response->setHeader('Allow:', 'OPTIONS, GET, POST, PUT, PATCH, DELETE');

       return $response;
   });
   // $routes->options('api/(:any)', static function () {});
});

I agree to receive announcements of interest about this Blog.

Let's configure CORS in C4 in a simple way.

- Andrés Cruz

En español

This material is part of my complete course and book; You can purchase them from the books and/or courses section, Curso y Libro CodeIgniter 4 desde cero + integración con Bootstrap 4 o 5 - 2025.