CodeIgniter跨域问题:React调用REST接口报Access-Control相关错误
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/loginendpoint (most default setups allow this, but it's worth confirming). - If you're using Apache, ensure your
.htaccessfile doesn't block OPTIONS requests—you can addAllowMethods GET POST OPTIONS PUT DELETEto 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

