Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CORS issue in codeigniter 4: Response to preflight request doesn't pass access control check

I'm making an api with Codeigniter 4 for a react application. Everything works fine in postman but when I make requests with axios (also tried fetch), it gets CORS error

Access to XMLHttpRequest at 'http://localhost:8080/testpost' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I tried adding headers to base controller:

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Methods: POST,GET, OPTIONS");
header("Access-Control-Allow-Headers: *");

Now it works fine with requests without JSON body, but when I send json body same error occurs.

axios.post("http://localhost:8080/testpost", { data: "test" })
    .then((response) => {
        console.log(response);
    })
    .catch((err) => {
        console.log("error!!!");
    });
// Routes.php
$routes->post('/testpost', 'Home::testPost');
// Home Controller
public function testPost()
{
    return $this->response->setJSON('test response');
}

Thanks for your help

like image 531
eminsh Avatar asked Oct 28 '25 10:10

eminsh


2 Answers

Please try by setting Apache response headers and redirect method to .htaccess in root of www/public directory, like this:

#Redirect for CORS Preflight request
RewriteCond %{REQUEST_METHOD} OPTIONS
RewriteRule ^(.*)$ $1 [R=200,L]
#Set headers to access CORS Requests / allowing localhost only
Header always add Access-Control-Allow-Origin "*"
Header always add Access-Control-Allow-Headers "origin, x-requested-with, content-type"
Header always add Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

NOTE: Be careful by adding Header always add Access-Control-Allow-Origin "*" to your .htaccess, "*" open doors for attackers, replace * with your domain or subdumain!

like image 191
Akash prajapati Avatar answered Oct 30 '25 01:10

Akash prajapati


On your index.php on public directory, just paste the following codes to set

headers for the response
header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
$method = $_SERVER['REQUEST_METHOD'];
if($method == "OPTIONS") {
die();
}

just before the response areaenter image description here

like image 39
ndotie Avatar answered Oct 29 '25 23:10

ndotie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!