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

CodeIgniter跨域问题:React调用REST接口报Access-Control相关错误

Fixing CORS Error Between CodeIgniter REST API and React

Hey there, let's break down why your React app is hitting that CORS error even though your API works perfectly in Postman!

The Root Issue

When you make a cross-domain request from a browser (like React running on localhost:3000 calling your CodeIgniter API at http://123.0.0.5:81), the browser first sends a preflight OPTIONS request to verify if the server allows the actual request. Postman skips this preflight step entirely, which is why it works there but fails in your React app.

Your current code sets the correct CORS headers, but it doesn't properly handle the OPTIONS request—so the browser gets an unexpected response during preflight, triggering the error you're seeing.

The Solution

Update your Auth controller's constructor to explicitly handle the OPTIONS request by returning a 200 status and exiting immediately. This tells the browser the request is allowed without running any extra controller logic.

Here's the modified controller code:

class Auth extends CI_Controller {
    function __construct() {
        parent::__construct();
        header('Access-Control-Allow-Origin: *');
        header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
        header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
        
        // Handle preflight OPTIONS request directly
        if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
            http_response_code(200);
            exit();
        }
    }

    // Your login method and other controller logic here...
}

Why This Works

  • The preflight OPTIONS request hits your controller's constructor, where we detect it, send the required CORS headers, and return a 200 status right away.
  • This satisfies the browser's preflight check, allowing it to proceed with the actual POST request from your React app.

Quick Extra Checks

  • Double-check that your CodeIgniter routes are configured to accept OPTIONS requests for the /auth/login endpoint (most default setups allow this, but it's worth confirming).
  • If you're using Apache, ensure your .htaccess file doesn't block OPTIONS requests—you can add AllowMethods GET POST OPTIONS PUT DELETE to your config if needed.

After making this change, test your React fetch call again—it should now work without the CORS error!

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:21:53