You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用Codeigniter+REST插件开发API,无法阻止CORS预检OPTIONS请求求助

Hey there, let's tackle this CORS pre-flight OPTIONS issue you're facing with CodeIgniter and its REST plugin—this is super common, so don't beat yourself up over it! The root problem here is that your API isn't sending the correct response headers when the browser sends an OPTIONS pre-flight request, so the browser blocks the actual API call. Here are a few proven fixes to get this sorted:

1. Add an OPTIONS Handler Directly in Your REST Controller

Most CodeIgniter REST controllers (like the popular REST_Controller from chriskacerguis) don't handle OPTIONS requests by default. So you can add a dedicated method in your API controller to respond to these pre-flight requests:

// Inside your API controller (e.g., Api.php)
public function index_options() {
    // Allow your frontend domain here—replace * with your actual domain in production!
    header("Access-Control-Allow-Origin: *");
    // List the HTTP methods your API supports
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    // Allow any custom headers your frontend sends (like Authorization or Content-Type)
    header("Access-Control-Allow-Headers: Content-Type, Authorization");
    
    // Pre-flight requests only need headers, no body—send a 200 and exit
    $this->output->set_status_header(200);
    exit();
}

If your controller has multiple methods (like users_get, users_post), you might need to add a corresponding users_options method too, or refactor to a generic OPTIONS handler that works for all endpoints.

2. Use CodeIgniter Hooks for Global CORS Handling

If you have multiple API controllers, adding an OPTIONS method to each one is tedious. Instead, use CodeIgniter's hooks to handle CORS globally for every request:

Step 1: Enable Hooks

Open application/config/config.php and set:

$config['enable_hooks'] = TRUE;

Step 2: Define the Hook

Open application/config/hooks.php and add this hook:

$hook['pre_controller'][] = array(
    'function' => 'handle_cors',
    'filename' => 'cors_hook.php',
    'filepath' => 'hooks'
);

Step 3: Create the Hook File

Make a new file at application/hooks/cors_hook.php with this code:

function handle_cors() {
    // Dynamically get the requesting origin (or use your frontend domain directly)
    $allowed_origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '*';
    
    header("Access-Control-Allow-Origin: {$allowed_origin}");
    header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
    header("Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With");
    
    // If it's an OPTIONS pre-flight request, send 200 and exit immediately
    if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
        http_response_code(200);
        exit();
    }
}

This will automatically handle OPTIONS requests for every endpoint in your API.

3. Check Your Server Configuration

Sometimes your web server (Apache/Nginx) might be intercepting OPTIONS requests before they even reach CodeIgniter. Here's how to fix that:

For Apache

Add these lines to your .htaccess file in the CodeIgniter root:

# Let OPTIONS requests pass through
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]

For Nginx

Add this block to your server configuration:

if ($request_method = OPTIONS) {
    return 200;
}

Quick Notes for Production

  • Never use * for Access-Control-Allow-Origin in production—replace it with your actual frontend domain (e.g., https://your-app.com) to avoid security risks.
  • If you're using the CodeIgniter REST Server plugin, double-check the $config['check_cors'] setting in application/config/rest.php—if it's enabled, make sure it's not conflicting with your manual header settings.

Give these fixes a try—start with the controller-level OPTIONS handler first to quickly test if it works, then move to the global hook if you need it across multiple endpoints.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 07:48:49