You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Ionic4 + Codeigniter遇CORS问题:预检请求未通过权限校验

Hey there, let's tackle this CORS issue you're facing with Ionic 4 and CodeIgniter. That preflight error is super common when cross-origin requests are involved, and it usually boils down to your CodeIgniter server not handling the OPTIONS preflight request correctly or missing critical CORS headers. Let's walk through the fixes step by step:

Fixing CORS Issue Between Ionic 4 and CodeIgniter

First, Let's Understand the Error

Access to XMLHttpRequest at 'http://somexxx.com//service/countries' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: It does not have HTTP ok status.

Browsers send an OPTIONS preflight request before your actual API call to verify if the server allows cross-origin requests. If your CodeIgniter server doesn't respond to this OPTIONS request with a 200 OK status and the right CORS headers, the browser blocks the main request entirely.


Solution 1: Server-Side Fix (CodeIgniter Configuration)

This is the proper, long-term fix—all CORS rules should be handled on the server. Here's how to set it up based on your CodeIgniter version:

For CodeIgniter 3

We'll use a custom hook to inject CORS headers and handle OPTIONS requests:

  1. Create a new file application/hooks/CorsHook.php with this code:
<?php
class CorsHook {
    public function handle() {
        // Allow specific origins (replace with your Ionic dev/prod URLs)
        $allowedOrigins = [
            'http://localhost:8100',
            'https://your-production-ionic-app.com'
        ];
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
        
        // Set allowed origin (use specific ones for production, * for testing)
        if (in_array($origin, $allowedOrigins)) {
            header("Access-Control-Allow-Origin: $origin");
        } else {
            header("Access-Control-Allow-Origin: *");
        }
        
        // Allow common HTTP methods and headers
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
        header("Access-Control-Max-Age: 86400"); // Cache preflight response for 1 day
        
        // Directly respond to OPTIONS requests with 200 OK
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit();
        }
    }
}
  1. Enable hooks in application/config/config.php:
$config['enable_hooks'] = TRUE;
  1. Register the hook in application/config/hooks.php:
$hook['pre_controller'][] = array(
    'class'    => 'CorsHook',
    'function' => 'handle',
    'filename' => 'CorsHook.php',
    'filepath' => 'hooks'
);

For CodeIgniter 4

CodeIgniter 4 has built-in CORS support—use the built-in filter:

  1. Open app/Config/Filters.php and enable the CORS filter for all requests:
public $globals = [
    'before' => [
        // ... keep your existing filters, add this line
        'cors',
    ],
    'after' => [
        'toolbar',
        // ... other filters
    ],
];
  1. Configure allowed origins/methods in app/Config/Cors.php:
public $allowedOrigins = [
    'http://localhost:8100',
    'https://your-production-app.com'
];
public $allowedMethods = ['GET', 'POST', 'OPTIONS', 'PUT', 'DELETE'];
public $allowedHeaders = ['Content-Type', 'Authorization', 'X-Requested-With'];
public $maxAge = 86400;

Solution 2: Quick Dev Workaround (Ionic Proxy)

If you're just in development and want to skip CORS checks temporarily, use an Ionic proxy:

  1. Create a proxy.conf.json file in your Ionic project root:
{
    "/service/*": {
        "target": "http://somexxx.com",
        "secure": false,
        "changeOrigin": true
    }
}
  1. Run your dev server with the proxy:
ionic serve --proxy-config proxy.conf.json
  1. Update your API calls in Ionic to use the relative path instead of the full URL:
// Instead of this:
this.http.get('http://somexxx.com/service/countries')

// Use this:
this.http.get('/service/countries')

Solution 3: Double-Check Your API Route

Make sure your service/countries route in CodeIgniter isn't protected by authentication middleware that blocks OPTIONS requests. Sometimes auth filters run before CORS headers are set, causing the preflight to fail. If that's the case, exclude OPTIONS requests from your auth checks.


Testing the Fix

After setting up the server-side CORS rules, open your browser's dev tools (Network tab) and check:

  • The OPTIONS request to service/countries returns a 200 OK status.
  • The response headers include Access-Control-Allow-Origin set to your Ionic origin (e.g., http://localhost:8100).

内容的提问来源于stack exchange,提问作者Gollapalli

火山引擎 最新活动