Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bug: Cors not working #9442

Closed
koloner opened this issue Feb 6, 2025 · 6 comments
Closed

Bug: Cors not working #9442

koloner opened this issue Feb 6, 2025 · 6 comments

Comments

@koloner
Copy link

koloner commented Feb 6, 2025

PHP Version

8.2

CodeIgniter4 Version

4.6.0

CodeIgniter4 Installation Method

Composer (using codeigniter4/appstarter)

Which operating systems have you tested for this bug?

Windows

Which server did you use?

apache

Database

mysql

What happened?

I am using CodeIgniter 4 for the backend as an API for a Vue.js site, but I am encountering a CORS error when trying to communicate between them.

How can I fix this issue?

Steps to Reproduce

I have already applied the following configurations:

Cors.php file

public array $api = [
    'allowedOrigins'         => ['http://localhost:5173'],
    'allowedOriginsPatterns' => [],
    'supportsCredentials'    => false,
    'allowedHeaders'         => ['Authorization', 'Content-Type','X-Requested-With'],
    'exposedHeaders'         => [],
    'allowedMethods'         => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
    'maxAge'                 => 7200,
];

Routes file

$routes->group('api/v1', ['namespace' => 'App\Controllers\Api','filter'=>'cors:api'], function (RouteCollection $routes) {
    $routes->match(['post', 'options'], 'auth/signup', 'AuthController::signup', ['as' => 'api_signup']);
});

Controller Class
I am using:

class AuthController extends ResourceController

However, I am still getting a CORS error, and I can't resolve it.

For running the backend and frontend, I use:

php spark serve
npm run dev

Expected Output

Image

Anything else?

No response

@koloner koloner added the bug Verified issues on the current code behavior or pull requests that will fix them label Feb 6, 2025
@neznaika0
Copy link
Contributor

Is this your case #9437 ?

@michalsn
Copy link
Member

michalsn commented Feb 6, 2025

This is not a CodeIgniter issue.

Are you using Vite? Have you set server.cors to true?

@michalsn michalsn removed the bug Verified issues on the current code behavior or pull requests that will fix them label Feb 6, 2025
@koloner
Copy link
Author

koloner commented Feb 7, 2025

idk what is problem but i can fix
my code

<?php

namespace App\Filters;

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

class CorsFilter implements FilterInterface
{
    /**
     * Do whatever processing this filter needs to do.
     * By default it should not return anything during
     * normal execution. However, when an abnormal state
     * is found, it should return an instance of
     * CodeIgniter\HTTP\Response. If it does, script
     * execution will end and that Response will be
     * sent back to the client, allowing for error pages,
     * redirects, etc.
     *
     * @param RequestInterface $request
     * @param array|null       $arguments
     *
     * @return RequestInterface|ResponseInterface|string|void
     */
    public function before(RequestInterface $request, $arguments = null)
    {
        $request->setHeader('Access-Control-Allow-Origin', '*');
        $request->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        $request->setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');

        return $request;
    }

    /**
     * Allows After filters to inspect and modify the response
     * object as needed. This method does not allow any way
     * to stop execution of other after filters, short of
     * throwing an Exception or Error.
     *
     * @param RequestInterface  $request
     * @param ResponseInterface $response
     * @param array|null        $arguments
     *
     * @return ResponseInterface|void
     */
    public function after(RequestInterface $request, ResponseInterface $response, $arguments = null)
    {
        $response->setHeader('Access-Control-Allow-Origin', '*');
        $response->setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
        $response->setHeader('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With');

        return $response;
    }
}

i am just add this file and not problem with vite
and for call this filter

$routes->group('api/v1', ['namespace' => 'App\Controllers\Api','filter' => ['CorsFilter','authApiFilter']], function (RouteCollection $routes) {
    $routes->post('auth/signup', 'AuthController::signup', ['as' => 'api_signup','public' => true]);
    $routes->options('auth/signup', 'AuthController::signup', ['as' => 'api_signup','public' => true]);
});

i think file settings cors file is not working

@michalsn
Copy link
Member

michalsn commented Feb 7, 2025

I made a standard Vite installation for Vue.

My App.vue file:

<template>
  <div>
    <h1>Vite + Vue + CORS Test</h1>
    <button @click="fetchData">Fetch Data from API</button>
    <p>{{ apiResponse }}</p>
  </div>
</template>

<script>
export default {
  data() {
    return {
      apiResponse: '',
    };
  },
  methods: {
    async fetchData() {
      try {
        const response = await fetch('http://localhost:8080/api/v1/auth/signup', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({ message: 'Hello from Vue' }),
        });
        const data = await response.json();
        this.apiResponse = JSON.stringify(data);
      } catch (error) {
        this.apiResponse = 'Error: ' + error.message;
      }
    },
  },
};
</script>

My sample AuthController.php file:

<?php

namespace App\Controllers\Api;

use CodeIgniter\HTTP\ResponseInterface;
use CodeIgniter\RESTful\ResourceController;

class AuthController extends ResourceController
{
    public function signup(): ResponseInterface
    {
        $message = $this->request->getJsonVar('message');

        $data = ['sample' => 'data', 'postMessage' => $message];

        return $this->respond($data, 200);
    }
}

Then I applied routes and cors config from your initial post. Everything is working fine, so I cannot reproduce the problem you're reporting.


In your second post, you're using also "authApiFilter" filter, so I'm guessing this is the issue - just like neznaika0 said.

Are you experiencing the same problems only when you're using the default cors:api filter without "authApiFilter"?

@koloner
Copy link
Author

koloner commented Feb 7, 2025

now i again test Cors.php file and that corrcet idk what is problem but now is fix my cors settings

public array $corsapi = [
        'allowedOrigins'         => ['http://localhost:5173'],
        'allowedOriginsPatterns' => [],
        'supportsCredentials'    => false,
        'allowedHeaders'         => ['Authorization', 'Content-Type','X-Requested-With','Accept','Origin'],
        'exposedHeaders'         => [],
        'allowedMethods'         => ['GET', 'POST', 'OPTIONS'],
        'maxAge'                 => 7200,
    ];

I think the problem was with the application cache. If you add an option that is in the env and automatically clears the cache between each serve request, it will be fixed.

@michalsn
Copy link
Member

michalsn commented Feb 7, 2025

Well, if everything is working, then I will close this issue. But feel free to continue the conversation if you notice something new.

@michalsn michalsn closed this as completed Feb 7, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants